首页 > 其他 > 详细

222. Count Complete Tree Nodes

时间:2016-10-20 07:50:52      阅读:186      评论:0      收藏:0      [点我收藏+]

Given a complete binary tree, count the number of nodes.

 

http://www.programcreek.com/2014/06/leetcode-count-complete-tree-nodes-java/

 

 public int CountNodes(TreeNode root) {
        if(root == null) return 0;
        var loop = root;
        int height =0;
        while(loop != null)
        {
            loop = loop.left;
            height++;
        }
        int res = (int)Math.Pow(2,height)-1;
        
        
        int leftHeight =0;
        int rightHeight=0;
        
        var left = root.left;
        var right = root.right;
        while(left != null)
        {
            left = left.left;
            leftHeight++;
        }
        while(right != null)
        {
            right = right.right;
            rightHeight++;
        }
        if(leftHeight == rightHeight) return (int)Math.Pow(2,leftHeight+1)-1;
        return 1+CountNodes(root.left)+CountNodes(root.right);
        
    }

 

222. Count Complete Tree Nodes

原文:http://www.cnblogs.com/renyualbert/p/5979389.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!