二叉树:20二叉搜索树的最近公共祖先

20二叉搜索树的最近公共祖先

本题的两个关键:

  1. 如何利用BST的性质来搜索
  2. 为何一个节点在pq中间,那么这个节点就一定是最近公共祖先
class Solution {
    //向下遍历,如果遍历到一个节点在pq中间,那么这个节点就一定是最近公共祖先
    TreeNode res = null;
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        TreeNode small = p.val > q.val ? q : p;
        TreeNode big = null;
        if(small != p) big = p;
        else big = q;
        res = traversal(root, small, big);
        return res;
    }
    TreeNode traversal(TreeNode root, TreeNode small, TreeNode big) {
        if(root == null) return root;
        // if(root == small || root == big) {}
        
        TreeNode left = null;
        TreeNode right = null;
        if(root.val > small.val && root.val > big.val){
            //最近公共祖先在左子树
            left = traversal(root.left, small, big);//返回值是本树的最近公共祖先
        }
        else if(root.val >= small.val && root.val <= big.val) {
            return root;
        }
        else if(root.val < small.val && root.val < big.val) {
            right = traversal(root.right, small, big);
        }
        if(left != null) return left;
        if(right != null) return right;
        return null;
    }
}
class Solution {
    //向下遍历,如果遍历到一个节点在pq中间,那么这个节点就一定是最近公共祖先
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null) return root;
        
        if(root.val > p.val && root.val > q.val){
            //最近公共祖先在左子树
            TreeNode left = lowestCommonAncestor(root.left, p, q);//返回值是本树的最近公共祖先
            if(left != null) return left;
        }
        if(root.val < p.val && root.val < q.val) {
            //公共祖先在右子树
            TreeNode right = lowestCommonAncestor(root.right, p, q);
            if(right != null) return right;
        }
        
        return root;
    }

}
class Solution {//迭代法
    //向下遍历,如果遍历到一个节点在pq中间,那么这个节点就一定是最近公共祖先
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null) return root;
        TreeNode cur = root;
        while(cur != null) {
            if(cur.val < p.val && cur.val < q.val) {
                cur = cur.right;
            }
            else if(cur.val > p.val && cur.val > q.val) {
                cur = cur.left;
            }
            else return cur;
        }
        return null;
    }

}

本题与19的遍历区别就是本题不必要遍历到pq,也就是说没必要见到pq,所以就没了遇见pq就返回这句话,本题思路也就是单纯遇到一个节点判断与pq大小关系从而来获取答案,而上面一题需要进行回溯也就是遍历过了pq才能得到答案。本题终止条件也就只有遇到空节点的返回,当然加上原先那句话不会出现错误

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

曦煜墨白

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值