-
Notifications
You must be signed in to change notification settings - Fork 319
/
Copy path236_LowestCommonAncestorOfBinaryTree.cpp
76 lines (72 loc) · 2.11 KB
/
236_LowestCommonAncestorOfBinaryTree.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
66
67
68
69
70
71
72
73
74
75
/*
* @Author: [email protected]
* @Last Modified time: 2016-09-16 12:35:32
*/
/**
* 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:
/*
Recursive method: DFS.
If the current (sub)tree contains both p and q, then the function result is their LCA.
If only one of them is in that subtree, then the result is that one of them.
If neither are in that subtree, the result is null/None/nil.
More version can be found here:
https://discuss.leetcode.com/topic/18561/4-lines-c-java-python-ruby
*/
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root==NULL || root==p || root==q){
return root;
}
TreeNode* l = lowestCommonAncestor(root->left, p, q);
TreeNode* r = lowestCommonAncestor(root->right, p, q);
if(l && r){
return root;
}
else{
return l ? l : r;
}
}
};
class Solution_2 {
public:
/*
Iteratice method.
*/
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
map<TreeNode*, TreeNode*> parent;
parent.insert({root, NULL});
queue<TreeNode*> que;
que.push(root);
// Build the relationship from child to parent
while(parent.find(p) == parent.end() || parent.find(q) == parent.end()){
TreeNode *cur = que.front();
que.pop();
if(cur->left){
que.push(cur->left);
parent.insert({cur->left, cur});
}
if(cur->right){
que.push(cur->right);
parent.insert({cur->right, cur});
}
}
// Trace brack from one node, record the path. Then trace from the other.
set<TreeNode*> ancestor;
while(p){
ancestor.insert(p);
p = parent[p];
}
while(ancestor.find(q) == ancestor.end()){
q = parent[q];
}
return q;
}
};