给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
例如,给定如下二叉树: root = [3,5,1,6,2,0,8,null,null,7,4]
这道题和236. 二叉树的最近公共祖先
一样。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
//三种情况:
//p和q分别在左右子树,递归
//p为root,当前节点为最近公共祖先
//q为root,当前节点为最近公共祖先
//出口
if (root == null) return null;
if (p == root || q == root) return root;
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
//不为空,即找到
//如果一个在左边找到,一个在右边找到
if (left != null && right != null) return root;
//左子树没找到,在右子树找到
else if (left == null) return right;
//右子树没找到,在左子树找到
else if (right == null) return left;
//都没找到
else return null;
}
}
这道题是,前一篇文章《【LeetCode】剑指 Offer 68 - I. 二叉搜索树的最近公共祖先(Java)
》的升级版,没什么头绪,看题解区Krahets
写的题解思路,做出来的,没看他写的代码。