这道题真的是做的我云里雾里的,先记一个笔记吧。
参考解答:
https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/solution/c-jing-dian-di-gui-si-lu-fei-chang-hao-li-jie-shi-/
Java 代码:
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public class Solution {
// 思路:
// 1、如果 p 和 q 都非空,返回它们的公共祖先
// 2、如果只存在一个,则返回存在的一个;
// 3、如果 p 和 q 都不存在,则返回空
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
// 初始条件:只要等于其中之一,就返回自己,作为后续判断的依据
// 既然是编写递归方法,首先先写出递归终止条件
// 【关键 2】
if (root == null || root == p || root == q) {
return root;
}
// 后序遍历
// 先在左子树中找,p 和 q 的最近公共祖先
TreeNode left = lowestCommonAncestor(root.left, p, q);
// 再在右子树中找,p 和 q 的最近公共祖先
TreeNode right = lowestCommonAncestor(root.right, p, q);
// 如果左边和右边两者都空,说明,p 和 q 分散在 root 的左右子树中
if (left != null && right != null) {
return root;
}
// 【关键 1】否则返回 left 和 right 中非空的那个
if (left == null) {
return right;
} else {
return left;
}
}
}