236. Lowest Common Ancestor of a Binary Tree
DFS
1 | /** |
抄的solution T(n) : O(n)
S(n) : O(n) 递归堆栈的大小
判断每个节点,当某一结点左边和右边或左边和中间或右边和中间包含目标时,返回那个节点
记录父亲再去遍历
先获取到所有对的父亲,直到p和q的父亲都有了再停止
然后随便挑一个获取到他的所有祖先
另外一个再往回遍历,若有交点,就是解 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/**
* 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:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
unordered_map<TreeNode*, TreeNode*> parent;
parent[root] = nullptr;
stack<TreeNode*> s;
s.push(root);
while(parent.find(p) == parent.end() || parent.find(q) == parent.end()) // 这里不能用!parent[p] || !parent[q],因为parent[root] = nullptr
{
auto tmp = s.top();
s.pop();
if(tmp->right)
{
parent[tmp->right] = tmp;
s.push(tmp->right);
}
if(tmp->left)
{
parent[tmp->left] = tmp;
s.push(tmp->left);
}
}
unordered_set<TreeNode*> ancestor;
while(parent.find(p) != parent.end())
{
ancestor.insert(p);
p = parent[p];
}
while(ancestor.find(q) == ancestor.end())
{
q = parent[q];
}
return q;
}
};
S(n) : O(n)