222. Count Complete Tree Nodes

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);
        
    }

 

posted @ 2016-10-20 04:54  咖啡中不塌缩的方糖  阅读(107)  评论(0编辑  收藏  举报