-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLCAofBT.cc
66 lines (45 loc) · 1.21 KB
/
LCAofBT.cc
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
#include "leet.h"
#include <algorithm>
#include <cstring>
class Solution{
public:
TreeNode *ans;
int solve(TreeNode *root, TreeNode *p, TreeNode *q) {
if (!root) {
return 0;
}
//cout << root->val << endl;
int left = solve(root->left, p, q);
//cout << "left: " << left << endl;
if (2 == left) {
return 2;
}
if (1 == left && (root == p || root == q)) {
ans = root;
return 2;
}
int right = solve(root->right, p, q);
//cout << "right: " << right << endl;
if (2 == right) {
return 2;
}
if (1 == right && (root == p || root == q || 1 == left)) {
ans = root;
return 2;
}
return left + right + ((root == p || root == q) ? 1 : 0);
}
TreeNode* lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q) {
ans = nullptr;
solve(root, p, q);
return ans;
}
};
int main(){
Solution slu;
auto tree = Serialize::treenode({1,2,3});
auto p = tree->left;
auto q = tree->right;
cout << slu.lowestCommonAncestor(tree, p, q)->val << endl;
return 0;
}