【LeetCode - 285】二叉搜索树中的顺序后继

1、题目描述

在这里插入图片描述

2、解题思路

  顺序后继就是中序遍历的下一个节点。

  1、如果节点 p 有右子树,那么,p 的顺序后继就在右子树的最左侧。

  2、如果节点 p 没有右子树,那么 p 的顺序后继在它的祖宗节点当中,需要从根节点进行先序遍历,记录上一个节点。

  当遍历到某一个节点时,它的上一个节点就是 p,那么当前节点就是 p 的后继节点。

3、解题代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        // 存在右子节点,则目标在右子树的最左侧
        TreeNode index = p;
        if (index.right != null) {
            index = index.right;
            while (index.left != null) {
                index = index.left;
            }
            return index;
        }
        int inorder = Integer.MIN_VALUE;
        Stack<TreeNode> stack = new Stack<>();
        // 不存在右子节点,则目标在祖宗节点当中
        while (!stack.isEmpty() || root != null) {
            // 1. go left till you can
            while (root != null) {
                stack.push(root);
                root = root.left;
            }

            // 2. all logic around the node
            root = stack.pop();
            // if the previous node was equal to p
            // then the current node is its successor
            if (inorder == p.val) return root;
            inorder = root.val;

            // 3. go one step right
            root = root.right;
        }
        return null;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值