LeetCode: 236. Lowest Common Ancestor of a Binary Tree

题目描述

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

Given the following binary tree: root = [3,5,1,6,2,0,8,null,null,7,4]

img

Example 1:

1
2
3
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The LCA of nodes 5 and 1 is 3.

Example 2:

1
2
3
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output: 5
Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

这题要在二叉树中寻找两个点的最低的ancestor。

思路就是用两次DFS,找到两个点p和点q,并且记录路径,最后找路径中最先出现的相同点就可以了。在找路径出现的相同点点时候,使用set来找。

代码实现

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
class Solution {
private:
int findNode(TreeNode* root, TreeNode* p, vector<TreeNode*>& path) {
path.push_back(root);

if (root == p) {
return 1;
}

if (root->left != NULL){
if (findNode(root->left, p, path))
return 1;
path.pop_back();
}

if (root->right != NULL){
if (findNode(root->right, p, path))
return 1;
path.pop_back();
}

return 0;
}

public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
set<TreeNode*> setNode;
vector<TreeNode*> path1, path2;

findNode(root, p, path1);
findNode(root, q, path2);

for (int i = 0; i < path1.size(); i++) {
setNode.insert(path1[i]);
}

for (int i = path2.size()-1; i >= 0; i--) {
if (setNode.find(path2[i])!=setNode.end())
return path2[i];
}
return NULL;
}
};