[LeetCode]Inorder Successor in BST

题目: Given a binary search tree and a node in it, find the in-order successor of that node in the BST.

返回一棵BST中给定节点的中序遍历后继节点。就是在中序遍历的顺序中,给定点下一个要遍历的点。

方法一:直观逻辑

在BST中,进行二分搜索,找到所给节点,然后判断:
1、所给节点p有右子节点,那么后继节点就是右子树的最左节点。
2、所给节点是孩子节点,且之前有父节点,那么依次取出父节点,直到某个n级的点是n-1级父节点的左子节点,那么后继节点就是n-1级父节点。

用一个栈记录遍历过的父节点,代码如下:

public class Solution {
    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        return dfs(root, p, new Stack<>());
    }

    private TreeNode dfs(TreeNode root, TreeNode p, Stack<TreeNode> stack) {
        if (root == null) return null;
        TreeNode res;
        if (p.val > root.val){
            stack.push(root);
            res = dfs(root.right, p, stack);
        }
        else if (p.val < root.val){
            stack.push(root);
            res = dfs(root.left, p, stack);
        }
        else {
            if (root.right != null){
                root = root.right;
                while (root.left != null) root = root.left;
                return root;
            }else if (stack.isEmpty()) return null;
            else {
                TreeNode cur = root;
                while (!stack.isEmpty()) {
                    if (stack.peek().left == cur) return stack.peek();
                    else cur = stack.pop();
                }
                return null;
            }
        }
        return res;
    }
}

方法二:分治思想

上面的代码很复杂度还可以,但是实现十分的复杂,采用分治的思想,去分析每一个节点。

对于每一个节点,如果目标节点小于当前节点,那么目标节点应该在左子树,同时后继节点可能由左子树中产生,然而如果左子树返回节点为空,那么后继节点其实就是当前节点。

如果目标节点大于或者等于当前节点,后继节点都一定在右子树中。

可得代码如下:

public TreeNode successor(TreeNode root, TreeNode p) {
  if (root == null)
    return null;
    //后继一定在右子树中
  if (root.val <= p.val) {
    return successor(root.right, p);
  } else {
  //后继在左子树或者是当前节点
    TreeNode left = successor(root.left, p);
    return (left != null) ? left : root;
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值