Question

Formatted question description: https://leetcode.ca/all/285.html

 285	Inorder Successor in BST

 Given a binary search tree (See Definition) and a node in it,
 find the in-order successor of that node in the BST.

 Example

 Given tree = [2,1] and node = 1:
     2
    /
   1
 return node 2.

 Given tree = [2,1,3] and node = 2:
   2
  / \
 1   3
 return node 3.

 Note:
     If the given node has no in-order successor in the tree, return null.
     It's guaranteed that the values of the tree are unique.

 Challenge
     O(h), where h is the height of the BST.

 @tag-tree

Algorithm

If the value of the root node is less than or equal to the value of the p node, it means that the successor node of p must be in the right subtree, so this function is recursively called on the right child node.

If the value of the root node is greater than the value of p, then it is possible that the root node is the successor of p, or a node in the left subtree is a successor of p, * So first call this function recursively on the left child node, * If it returns empty, indicating that the root node is a successor node, just return, * If it is not empty, return that node

Code

Java

public class Inorder_Successor_in_BST {

    /**
     * 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) {

            if (root == null) {
                return null;
            }

            if (root.val <= p.val) {
                return inorderSuccessor(root.right, p);
            }
            else {
                TreeNode left = inorderSuccessor(root.left, p); //如果不是null,那么root就不是next
                return left == null ? root : left;
            }

        }
    }

}

All Problems

All Solutions