-
Notifications
You must be signed in to change notification settings - Fork 288
/
Copy pathAC_binary_search_lognlogn.cpp
66 lines (59 loc) · 1.5 KB
/
AC_binary_search_lognlogn.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
56
57
58
59
60
61
62
63
64
65
/*
* Author: illuz <iilluzen[at]gmail.com>
* File: AC_binary_search_lognlogn.cpp
* Create Date: 2015-08-06 09:56:20
* Descripton:
*/
#include <bits/stdc++.h>
using namespace std;
const int N = 0;
// 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 left_depth = getLeftDepth(root);
int right_depth = getRightDepth(root);
if (left_depth == right_depth) {
return (1 << left_depth) - 1;
} else {
return countNodes(root->left) + countNodes(root->right) + 1;
}
}
private:
int getRightDepth(TreeNode* root) {
if (root) return getRightDepth(root->right) + 1;
return 0;
}
int getLeftDepth(TreeNode* root) {
if (root) return getLeftDepth(root->left) + 1;
return 0;
}
};
int main() {
TreeNode root(0);
TreeNode l1(0);
TreeNode l2(0);
TreeNode l3(0);
TreeNode l4(0);
TreeNode l5(0);
Solution s;
cout << s.countNodes(&root) << endl;
root.left = &l1;
cout << s.countNodes(&root) << endl;
root.right = &l2;
cout << s.countNodes(&root) << endl;
l1.left = &l3;
cout << s.countNodes(&root) << endl;
l1.right = &l4;
cout << s.countNodes(&root) << endl;
l2.left = &l5;
cout << s.countNodes(&root) << endl;
return 0;
}