-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathp222.c
42 lines (40 loc) · 929 Bytes
/
p222.c
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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int f(struct TreeNode *root, int leftheight) {
if (root == NULL) return 0;
if (root->left == NULL) return 1;
if (root->right == NULL) return 2;
struct TreeNode *node = root->right;
int height = 1;
while (node != NULL)
{
height++;
node = node->left;
}
if (height == leftheight)
{
return (1<<(height-1))+f(root->right, height-1);
}
else
{
return (1<<(height-1))+f(root->left, leftheight-1);
}
}
int countNodes(struct TreeNode* root) {
if (root == NULL) return 0;
if (root->left == NULL) return 1;
int leftheight = 1;
struct TreeNode *node = root->left;
while (node != NULL)
{
leftheight++;
node = node->left;
}
return f(root, leftheight);
}