-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day 159: Lowest Common Ancestor in a BST.cpp
48 lines (37 loc) · 1.29 KB
/
Day 159: Lowest Common Ancestor in a BST.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
class Solution{
public:
Node* LCA(Node *root, int n1, int n2)
{
vector<Node *> patha, pathb;
bool founda, foundb;
founda = foundb = 0;
function<void(Node *)> traverse = [&](Node * node) {
if(node == nullptr)
return;
if(!founda)
patha.push_back(node);
if(!foundb)
pathb.push_back(node);
if(n1 == node -> data)
founda = 1;
if(n2 == node -> data)
foundb = 1;
traverse(node -> left);
traverse(node -> right);
if(!founda)
patha.pop_back();
if(!foundb)
pathb.pop_back();
};
traverse(root);
Node * ans = root;
int ind = 0;
while(ind < patha.size() and ind < pathb.size()){
if(patha[ind] == pathb[ind])
ans = patha[ind++];
else
break;
}
return ans;
}
};