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.
Hide Tags Tree Binary Search
Hide Similar Problems (E) Closest Binary Search Tree Value
這道題費了不少時間。
首先complete binary tree 就是除了最後一層可能不滿,其他層都是滿的。 其次如果一個binary tree heigh 是h,則它的node一共有pow(2,h)-1。這個冪指數函數又等價於 (1<<h)
。知道這幾點,我們就知道總的node 數爲
下面這個code最快,還需要好好理解一下,基本就是tmp找到了最後一個node的位置。。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int countNodes(TreeNode* root) {
if(!root) return 0;
TreeNode *temp = root;
int height = 0, count = 0, level;
while(temp) {
temp = temp->left;
height ++;
}
temp = root;
level = height - 2;
while(level >= 0) {
TreeNode *left = temp->left;
for(int i = 0;i < level;i ++) {
left = left->right;
}
if(left) {//which means there might be more node in right sub part, then tmp goes rightward.
temp = temp->right;
count += (1 << level);
} else temp = temp->left;
level --;
}
if(temp) count ++;
return (1 << (height - 1)) + count - 1;
}
};
傳統recursion比較好理解, 但時間複雜度較高: O(h^2).
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int countNodes(TreeNode* root) {
if(!root) return 0;
TreeNode* l = root;
TreeNode* r = root;
int cntL = 0, cntR = 0;
while(l){
++cntL;
l = l->left;
}
while(r){
++cntR;
r = r->right;
}
if(cntL == cntR) return (1 << cntL) - 1;
else return 1 + countNodes(root->left) + countNodes(root->right);
}
};