[LeetCode] Count Complete Tree Nodes

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

In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.

 

     其实不太懂为啥这道题会是medium,个人觉得这道题其实不难。因为说了是complete的BTS,所以呢如果左右两边node的height一致,那么就可以用公式((2^height)-1)来计算node数,如果不相等的话,就用老办法countNodes(root.left)+countNodes(root.right)+1。

     要注意的是代码中的getLeftHeight method的得出来的height其实比实际高度少1(因为判断的是n.left!=null)。

     原因在于写2<<(left)-1这里,在shift from 2 instead of 1的时候,已经有了implicit +1,所以呢就算是真实的height,在写入这里的时候也要-1。大概就是这个会比较容易忘记吧……因为我就忘记了哈哈哈哈。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int countNodes(TreeNode root) {
        if(root==null){
            return 0;
        }
        int left=getLeftHeight(root);
        int right=getRightHeight(root);
        if(left==right){
            return (2<<(left))-1;
        }else{
            return countNodes(root.left)+countNodes(root.right)+1;
        }
        
    }
    public int getLeftHeight(TreeNode tree){
        if(tree==null){
            return 0;
        }
        int height=0;
        while(tree.left!=null){
            height++;
            tree=tree.left;
        }
        return height;
    }
    public int getRightHeight(TreeNode tree){
        if(tree==null){
            return 0;
        }
        int height=0;
        while(tree.right!=null){
            height++;
            tree=tree.right;
        }
        return height;
    }
}

 

posted @ 2015-08-12 09:43  李小橘er  阅读(263)  评论(0)    收藏  举报