LeetCode 285 / LintCode 448 Inorder Successor in BST

54 篇文章 2 订阅
13 篇文章 0 订阅

思路

  • 思路1: 直接递归寻找后继,不考虑BST的性质,当作一般的二叉树来考虑。用递归很容易实现。
    时间复杂度O(n),空间复杂度O(log n)(递归栈)
  • 思路2:考虑BST的性质,类似二分的思想(为了O(h)的复杂度)。每次将p与root的值进行对比:(1)p>=root, 则搜索右子树;
    (2)p<root, 则搜索左子树,后继存在两种可能性:root或者左子树中的某个节点。如果在左子树中没搜到(null),则说明为root;否则为搜到的结果。【可以拿一棵3个节点的树来思考,always思考最简单的情况来递归给出定义】
    时间复杂度O(h)=O(logn), 空间复杂度O(h)

代码

  • 思路1
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */


public class Solution {
    /*
     * @param root: The root of the BST.
     * @param p: You need find the successor node of p.
     * @return: Successor of p.
     */
    TreeNode prev = null, res = null;
    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        // write your code here
        // prev = root;
        inorder(root, p);
        return res;
    }
    
    public void inorder(TreeNode root, TreeNode p) {
        if(root == null) return;
        inorder(root.left, p);
        if(prev == p) {
            res = root;
        }
        prev = root;
        inorder(root.right, p);
    }
}
  • 思路2
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */


public class Solution {
    /*
     * @param root: The root of the BST.
     * @param p: You need find the successor node of p.
     * @return: Successor of p.
     */
    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        // write your code here
        if(root == null || p == null)
            return null;
        
        if(root.val <= p.val) {
            return inorderSuccessor(root.right, p);
        } else {
            TreeNode leftRes = inorderSuccessor(root.left, p);
            return (leftRes == null) ? root : leftRes;
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值