给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
例如,给定如下二叉树: root = [3,5,1,6,2,0,8,null,null,7,4]
示例 1:
输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
输出: 3
解释: 节点 5 和节点 1 的最近公共祖先是节点 3。
示例 2:
输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
输出: 5
解释: 节点 5 和节点 4 的最近公共祖先是节点 5。因为根据定义最近公共祖先节点可以为节点本身。
说明:
所有节点的值都是唯一的。
p、q 为不同节点且均存在于给定的二叉树中。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || root == p || root == q ) {
return root;
}
TreeNode leftCommonAncestor = lowestCommonAncestor(root.left, p, q);
TreeNode rightCommonAncestor = lowestCommonAncestor(root.right, p, q);
//在左子树中没有找到,那一定在右子树中
if(leftCommonAncestor == null){
return rightCommonAncestor;
}
//在右子树中没有找到,那一定在左子树中
if(rightCommonAncestor == null){
return leftCommonAncestor;
}
//不在左子树,也不在右子树,那说明是根节点
return root;
}
}
对于 lowestCommonAncestor 这个函数的理解的话,它不一定可以返回最近的共同祖先,如果子树中只能找到 p 节点或者 q 节点,它最终返回其实就是 p 节点或者 q 节点。这其实对应于最后一种情况,也就是 leftCommonAncestor 和 rightCommonAncestor 都不为 null,说明 p 节点和 q 节点分处于两个子树中,直接 return root。
相对于解法一的话快了很多,因为不需要每次都遍历一遍二叉树,这个解法所有节点只会遍历一次。
root 节点一定是 p 节点和 q 节点的共同祖先,只不过这道题要找的是最近的共同祖先。
从 root 节点出发有一条唯一的路径到达 p。
从 root 节点出发也有一条唯一的路径到达 q。
可以抽象成下图的样子。
root
|
|
|
r
/ \
/ \
/ /
\ \
p \
q
事实上,我们要找的最近的共同祖先就是第一次出现分叉的时候,也就是上图中的 r。
那么怎么找到 r 呢?
我们可以把从 root 到 p 和 root 到 q 的路径找到,比如说是
root -> * -> * -> r -> x -> x -> p
root -> * -> * -> r -> y -> y -> y -> y -> q
然后我们倒着遍历其中一条路径,然后看当前节点在不在另一条路径中,当第一次出现在的时候,这个节点就是我们要找到的最近的公共祖先了。
比如倒着遍历 root 到 q 的路径。
依次判断 q 在不在 root 到 p 的路径中,y 在不在? ... r 在不在? 发现 r 在,说明 r 就是我们要找到的节点。
代码实现的话,因为我们要倒着遍历某一条路径,所以可以用 HashMap 来保存每个节点的父节点,从而可以方便的倒着遍历。
另外我们要判断路径中有没有某个节点,所以我们要把这条路径的所有节点存到 HashSet 中方便判断。
寻找路径的话,我们一开始肯定不知道该向左还是向右,所以我们采取遍历整个树,直到找到了 p 和 q ,然后从 p 和 q 开始,通过 hashMap 存储的每个节点的父节点,就可以倒着遍历回去确定路径。
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
Stack<TreeNode> stack = new Stack<>();
HashMap<TreeNode, TreeNode> parent = new HashMap<>();
stack.push(root);
parent.put(root, null);
//将遍历过程中每个节点的父节点保存起来
while (!parent.containsKey(p) || !parent.containsKey(q)) {
TreeNode cur = stack.pop();
if (cur.left != null) {
stack.push(cur.left);
parent.put(cur.left, cur);
}
if (cur.right != null) {
stack.push(cur.right);
parent.put(cur.right, cur);
}
}
HashSet<TreeNode> path = new HashSet<>();
// 倒着还原 p 的路径,并将每个节点加入到 set 中
while (p != null) {
path.add(p);
p = parent.get(p);
}
// 倒着遍历 q 的路径,判断是否在 p 的路径中
while (q != null) {
if (path.contains(q)) {
break;
}
q = parent.get(q);
}
return q;
}
作者:windliang
链接:https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by-5-2/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。