-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNo_0236_LowestCommonAncestorBT.h
94 lines (91 loc) · 1.61 KB
/
No_0236_LowestCommonAncestorBT.h
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#pragma once
#include "No_0_common.h"
class No_236
{
public:
void FindPath(TreeNode* root, TreeNode* target, vector<TreeNode*>& path, bool& stop)
{
if (!root||stop)
{
return;
}
if (root->val == target->val)
{
stop = true;
path.push_back(root);
return;
}
FindPath(root->left, target, path, stop);
if (stop)
{
path.push_back(root);
return;
}
FindPath(root->right, target, path, stop);
if (stop)
{
path.push_back(root);
return;
}
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q)
{
vector<TreeNode*> pathP;
vector<TreeNode*> pathQ;
bool stop = false;
FindPath(root, p, pathP, stop);
stop = false;
FindPath(root, q, pathQ, stop);
int startP = 0;
int startQ = 0;
if (pathP.size() > pathQ.size())
{
startP += (pathP.size() - pathQ.size());
}
else
{
startQ += (pathQ.size() - pathP.size());
}
while (pathP[startP]!=pathQ[startQ])
{
++startQ;
++startP;
}
return pathP[startP];
}
TreeNode* result = NULL;
bool Recursion(TreeNode* root, TreeNode* p, TreeNode* q)
{
if (!root)
{
return false;
}
if (result)
{
return false;
}
int count = 0;
if (root->val == p->val || root->val == q->val)
{
++count;
}
if (Recursion(root->left, p, q))
{
++count;
}
if (Recursion(root->right, p, q))
{
++count;
}
if (count >= 2)
{
result = root;
}
return count > 0;
}
TreeNode* lowestCommonAncestor2(TreeNode* root, TreeNode* p, TreeNode* q)
{
Recursion(root, p, q);
return result;
}
};