码迷,mamicode.com
首页 > 其他好文 > 详细

222. Count Complete Tree Nodes

时间:2016-10-20 07:53:17      阅读:154      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!