[LC] 285. Inorder Successor in BST

Posted xuanlu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LC] 285. 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.

The successor of a node p is the node with the smallest key greater than p.val.

 

Example 1:

技术图片

Input: root = [2,1,3], p = 1
Output: 2
Explanation: 1‘s in-order successor node is 2. Note that both p and the return value is of TreeNode type.

/**
 * 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 res = null;
        while (root != null) {
            if (root.val <= p.val) {
                root = root.right;
            } else {
                // only when p.val < root, root can possibly be the successor, continue check root.left
                res = root;
                root = root.left;
            }
        }
        return res;
    }
}

 

Good Reference: https://leetcode.com/problems/inorder-successor-in-bst/discuss/72653/Share-my-Java-recursive-solution

以上是关于[LC] 285. Inorder Successor in BST的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 285: Inorder Successor in BST

285. Inorder Successor in BST

285. Inorder Successor in BST - Medium

LeetCode 285. Inorder Successor in BST

[LeetCode] 285. Inorder Successor in BST

[LeetCode] 285. Inorder Successor in BST 二叉搜索树中的中序后继节点