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.
1. 递归
//return -1 if it is not.
int isCompleteTree(TreeNode* root) {
if (!root) return ; int cnt = ;
TreeNode *left = root, *right = root;
for(; left && right; left=left->left, right=right->right) {
cnt *= ;
} if (left!=NULL || right!=NULL) {
return -;
}
return cnt-;
} int countNodes(TreeNode* root) {
int cnt = isCompleteTree(root);
if (cnt != -) return cnt;
int leftCnt = countNodes(root->left);
int rightCnt = countNodes(root->right);
return leftCnt + rightCnt + ;
}
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) {
int ans = , lh = , rh = ;
TreeNode *p = root;
while(p)
{
//先求p的左右子树的最大深度。若相等,则p加左子树节点个数为1<<lh,再求右子树;若不等,则p加右子树节点个数为1<<rh,再求左子树。
if(!lh) //若lh不为0,说明lh由之前的lh--得到,是已知的。
{
for(TreeNode *t = p->left; t; t = t->left)
lh++;
}
for(TreeNode *t = p->right; t; t = t->left)
rh++;
if(lh == rh)
{
ans += << lh;
p = p->right;
}
else
{
ans += << rh;
p = p->left;
}
lh--;
rh = ;
}
return ans;
}
};