第 19 日:二叉搜索树的最近公共祖先
题目链接:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-zui-jin-gong-gong-zu-xian-lcof/
题目
解题
-
递归
解题思路:
注意这是二叉搜索树,也就是比当前结点小的都在左子树,比当前结点大的都在右子树。如果要作为两个结点的公共祖先,有一个特征就是两个结点分别在左右子树或者为其中一个结点本身,也就说我们只去遍历两个结点在root结点
同一子树的地方,当遇到第一个不满足条件的root结点
,则此root
就是结果。详细代码如下:
/**
* 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) {
TreeNode parent=null;
if(root.val>p.val&&root.val>q.val) parent=lowestCommonAncestor(root.left,p,q);
if(root.val<p.val&&root.val<q.val) parent=lowestCommonAncestor(root.right,p,q);
if(parent!=null) return parent;
return root;
}
}
-
遍历
解题思路:
思路和递归差不多,只不过空间复杂度从O(N)变到O(1);详细代码如下:
/**
* 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) {
TreeNode node=null;
while(node==null){
if(root.val>p.val&&root.val>q.val) {
root=root.left;
continue;
}
if(root.val<p.val&&root.val<q.val) {
root=root.right;
continue;
}
node=root;
break;
}
return node;
}
}