给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
例如,给定如下二叉搜索树: root = [6,2,8,0,4,7,9,null,null,3,5]
可参考二叉树的最近公共祖先,结合二叉搜索树特点;
得到从从根节点到p,q的路径,出现最后一次出现相同点为最近公共祖先
上代码:
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
TreeNode ancestor = root;
while (true) {
//p q 都在左子树
if (p.val < ancestor.val && q.val < ancestor.val) {
ancestor = ancestor.left;
}
//p q 都在右子树
else if (p.val > ancestor.val && q.val > ancestor.val) {
ancestor = ancestor.right;
}
//p q 分岔了
else {
break;
}
}
return ancestor;
}
}
最难不过坚持!