8.8 LeetCode 222 Count Complete Tree Nodes

Question:

Count Complete Tree Nodes

 Total Accepted: 11040 Total Submissions: 53992My Submissions

 

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

Definition of a complete binary tree from Wikipedia:
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.

Analysis:

Steps to solve this problem:
1) get the height of left-most part
2) get the height of right-most part
3) when they are equal, the # of nodes = 2^h -1
4) when they are not equal, recursively get # of nodes from left&right sub-trees

public int countNodes(TreeNode root) { // Notice the traditional traversal will exceed the time limit and we also can't use Math.pow() cause it is too slow.
        if(root == null) return 0;
        TreeNode ln = root, rn = root;
        int l = 0, r = 0;
        while(ln != null) {
            l++;
            ln = ln.left;
        }
        while(rn != null) {
            r++;
            rn = rn.right; 
        }
     // Math.pow(2,n) = 2<<(n-1) e.g. 2^1 == 2 == 2<<0 
        if(l == r) return (2<<(l - 1)) - 1; // notice "<<" is right connect so we need "() out of 2<<(l-1)" 
        return 1 + countNodes(root.left) + countNodes(root.right);
    }  

 

posted @ 2015-08-08 22:48  YoungAndSimple  阅读(126)  评论(0编辑  收藏  举报