Count Complete Tree Nodes

Desicription

Given a complete binary tree, count the number of nodes.

Note:

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:

1
2
3
4
5
6
Input:
1
/ \
2 3
/ \ /
4 5 6

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public:
int countNodes(TreeNode* root) {
return countAll(root, -1, -1);
}
int countAll(TreeNode* root, int left_depth, int right_depth) {
if(left_depth == -1) {
left_depth = leftDepth(root);
}
if(right_depth == -1) {
right_depth = rightDepth(root);
}
if(left_depth == right_depth) {
return static_cast<int>(pow(2, left_depth) - 1);
}
return 1 + countAll(root->left, left_depth - 1, -1) + countAll(root->right, -1, right_depth - 1);
}
int leftDepth(TreeNode* root) {
if(root == nullptr) {
return 0;
}
return 1 + leftDepth(root->left);
}
int rightDepth(TreeNode* root) {
if(root == nullptr) {
return 0;
}
return 1 + rightDepth(root->right);
}
};