0%

236. Lowest Common Ancestor of a Binary Tree

O(n) 分治

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
/**
* 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:
// 在root为根的二叉树中找A,B的LCA:
// 如果找到了就返回这个LCA
// 如果只碰到A,就返回A
// 如果只碰到B,就返回B
// 如果都没有,就返回null
// 这里默认树上一定有p和q,所以不一定要真的把p和q都找到,假设只找到了其中一个,没找到另一个,说明找到的这个就是lca,另一个一定在以找到的这个点为根的树上
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (!root || root == p || root == q) return root;
auto l = lowestCommonAncestor(root->left, p, q);
auto r = lowestCommonAncestor(root->right, p, q);
if (l && r) return root;
return l ? l : r;
}
};
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
/**
* 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) {
TreeNode *res;
lca(root, p, q, res);
return res;
}

void lca(TreeNode* root, TreeNode* p, TreeNode* q, TreeNode *&res) {
if (!root || root == p || root == q) {
res = root;
return;
}
TreeNode *l, *r;
lca(root->left, p, q, l);
lca(root->right, p, q, r);
if (!l) {
res = r;
} else if (!r) {
res = l;
} else {
res = root;
}
}
};