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

8.8 LeetCode 222 Count Complete Tree Nodes

时间:2015-08-09 00:18:23      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:

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

 

8.8 LeetCode 222 Count Complete Tree Nodes

标签:

原文地址:http://www.cnblogs.com/michael-du/p/4714105.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!