04.06 后继者

原题目

面试题 04.06. 后继者

设计一个算法,找出二叉搜索树中指定节点的“下一个”节点(也即中序后继)。

如果指定节点没有对应的“下一个”节点,则返回null

示例 1:

输入: root = [2,1,3], p = 1

  2
 / \
1   3

输出: 2

示例 2:

输入: root = [5,3,6,2,4,null,null,1], p = 6

      5
     / \
    3   6
   / \
  2   4
 /   
1

输出: null




第一遍解法

中序遍历二叉搜索树,元素值递增。用pre来保存上一个节点,若上一个节点与p相等(pre == p),则返回当前节点(root)。

class Solution {
    private TreeNode pre = null;
    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        if (root == null) {
            return null;
        }

        TreeNode L = inorderSuccessor(root.left, p);
        if (pre != null && pre == p) {
            pre = root;     // 这一步是必要的,不然后续pre将一直等于p,最终返回根节点。
            return root;
        } 
        pre = root;
        TreeNode R = inorderSuccessor(root.right, p);

        if (L != null) {
            return L;
        }
        if (R != null) {
            return R;
        }
        return null;
    }
}

时间复杂度: O(n)

空间复杂度: O(n)



网上好的解法

我自己太死板了,遇到线索二叉树就一直想着中序遍历,当然这没有问题,但是在空间复杂度上会比较高。

这道题目告诉自己,就算遇到线索二叉树也要具体分析。

因为这题就是想找一个与p一样的节点,根据线索二叉树的性质,若p小于root就在左子树去找,若p大于root就去右子树找,依次往下找就可以了。

class Solution {
    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        //问题的本质是找到最靠近p节点且值大于p节点值的那个节点
        TreeNode res = root;
        //设定临时变量方便对树的操作
        TreeNode temp = root;
        while (temp != null){
            //如果当前节点的值小于等于目标节点的值,那一定不是答案节点,且答案节点在该节点的右孩子中
            if (temp.val <= p.val) {
                temp = temp.right;
            } else {
                //如果当前节点的值大于目标节点的值,那么该节点有可能是答案节点,具体是不是需要遍历其左孩子,寻找更靠近p节点值的答案
                res = temp;
                temp = temp.left;
            }
        }
        return res.val <= p.val ? null : res;
    }
}

作者:ShiningShar
链接:https://leetcode-cn.com/problems/successor-lcci/solution/javashuang-bai-by-shiningshar-2/
来源:力扣(LeetCode)

时间复杂度: O(n)

空间复杂度: O(1)



最后的代码

与网上代码一致。

class Solution {
    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        TreeNode res = root;
        TreeNode temp = root;
        while (temp != null){
            if (p.val >= root.val) {
                temp = temp.right;
            } else {
                res = temp;
                temp = temp.left;
            }
        }
        return res.val <= p.val ? null : res;
    }
}

时间复杂度: O(n)

空间复杂度: O(1)



小结

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值