题目

代码
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null) return null;
if (root == p || root == q) return root;
//两个递归返回的是root!
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
//必须满足到了到了一个子节点的母节点或者运行到最后了才会到这一步
if (left != null && right != null) return root;
if (left != null) return left;
if (right != null) return right;
return null;
}
}
结果

本文提供了一种解决二叉树最近公共祖先问题的有效算法。通过递归方式,该方法能够准确地找到两个指定节点的最近公共祖先。代码简洁且易于理解。
249

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



