public TreeNode commonAncestor (TreeNode root, int p, int q) {
if (null == root) return null;
if (root.val == p || root.val == q) return root;
// 通过递归假设我们知道了运算结果 题目含义是不会出现重复节点
TreeNode left = commonAncestor(root.left, p, q);
TreeNode right = commonAncestor(root.right, p, q);
if (left == null) return right;
else if (right == null) return left;
else return root;
}
public int lowestCommonAncestor (TreeNode root, int p, int q) {
// write code here
return commonAncestor(root, p, q).val;
}
二叉搜索树的最近公共祖先
二叉树公共祖先查找
最新推荐文章于 2025-12-02 18:57:44 发布
1960

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



