二叉树进阶题
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。(最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”)
p 和 q 均存在于给定的二叉树中。
思路
自上而下的深度遍历DFS。理解下面这个图,然后看代码注释。

代码
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
//空树 是没有公共祖先的
if(root == null) return null;
//root等于p,q中的某一个 ,返回给leftTree/rightTree
if(root == p || root == q) {
return root;
}
//遍历左子树
TreeNode leftTree = lowestCommonAncestor(root.left,p,q);
//遍历右子树
TreeNode rightTree = lowestCommonAncestor(root.right,p,q);
//当左右子树都不为空,那么公共祖先为root
if(leftTree != null && rightTree != null) {
return root;
}
//leftTree为空,rightTree不为空,那么祖先就是rightTree
if(leftTree == null && rightTree != null) {
return rightTree;
}
//leftTree不为空,rightTree为空,那么祖先就是leftTree
if(leftTree != null && rightTree == null) {
return leftTree;
}
//leftTree为空,rightTree为空,那么祖先就是没有公共祖先(理论上可以不需要这个判断,因为p,q存在于给定子树中)
if(leftTree == null && rightTree == null) {
return null;
}
return null;
}
本文解析了如何通过深度优先搜索(DFS)在给定的二叉树中找到两个指定节点的最近公共祖先,提供了详细的思路和代码实例。理解并掌握自顶向下遍历策略,有助于解决二叉树的经典问题。
2072

被折叠的 条评论
为什么被折叠?



