Problem

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.

Solution

/**
* 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->left;
TreeNode *r = root->right;

int l_depth = 1;
int r_depth = 1;
while(l)
{
l = l->left;
++l_depth;
}

while(r)
{
r = r->right;
++r_depth;
}

if(l_depth == r_depth)
return (1 << l_depth) - 1;

return countNodes(root->left) + 1 + countNodes(root->right);

}
};

• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 打赏

打赏

Bryan要加油

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 举报
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文

05-06 208
07-29 1288
08-12 1677
06-06 33
05-03 119