forked from wisdompeak/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path222.Count-Complete-Tree-Nodes_v1.cpp
55 lines (51 loc) · 1.18 KB
/
222.Count-Complete-Tree-Nodes_v1.cpp
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/**
* 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==NULL) return 0;
int ret = 1;
int h1 = findLeftDepth(root->left);
int h2 = findRightDepth(root->left);
int h3 = findLeftDepth(root->right);
int h4 = findRightDepth(root->right);
if (h1==h2)
{
ret += pow(2,h1)-1;
return ret+countNodes(root->right);
}
else
{
ret += pow(2,h3)-1;
return ret+countNodes(root->left);
}
}
int findLeftDepth(TreeNode* node)
{
int count = 0;
while (node!=NULL)
{
count++;
node=node->left;
}
return count;
}
int findRightDepth(TreeNode* node)
{
int count = 0;
while (node!=NULL)
{
count++;
node=node->right;
}
return count;
}
};