1 题目
Given a complete binary tree, count the number of nodes.
Note:
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.
Example:
Input:
1
/ \
2 3
/ \ /
4 5 6
Output: 6
2 尝试解
class Solution {
public:
int countNodes(TreeNode* root) {
if(root == NULL)return 0;
int result = 0;
queue<TreeNode*> saver;
saver.push(root);
while(!saver.empty()){
queue<TreeNode*>temp;
while(!saver.empty()){
TreeNode* cur = saver.front();
result += 1;
saver.pop();
if(cur->left != NULL) temp.push(cur->left);
if(cur->right != NULL) temp.push(cur->right);
}
saver.swap(temp);
}
return result;
}
};
3 标准解
class Solution {
public:
int countNodes(TreeNode* root) {
if(!root) return 0;
int hl=0, hr=0;
TreeNode *l=root, *r=root;
while(l) {hl++;l=l->left;}
while(r) {hr++;r=r->right;}
if(hl==hr) return pow(2,hl)-1;
return 1+countNodes(root->left)+countNodes(root->right);
}
};