二叉树的最近公共祖先该怎么理解,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
题目:给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
三种情况讨论:
如果p和q分别是root的左右节点,那么root就是我们要找的最近公共祖先
如果p和q都是root的左节点,那么返回lowestCommonAncestor(root.left,p,q)
如果p和q都是root的右节点,那么返回lowestCommonAncestor(root.right,p,q)
class
Solution {
public
TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if
(root == null)
return
root;
if
(p == root || q == root)
return
root;
TreeNode rleft = lowestCommonAncestor(root.left, p, q);
TreeNode rright = lowestCommonAncestor(root.right, p , q);
if
(rleft == null)
return
rright;
if
(rright == null)
return
rleft;
return
root;
// 此时是 p 和 q 节点再root节点的 左右两边
}
}
关于二叉树的最近公共祖先该怎么理解问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注天达云行业资讯频道了解更多相关知识。