LeetCode 0285. Inorder Successor in BST Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0285. Inorder Successor in BST

Description

Given the root of a binary search tree and a node p in it, return the in-order successor of that node in the BST. If the given node has no in-order successor in the tree, return null.

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.

Example 2:

Input: root = [5,3,6,2,4,null,null,1], p = 6
Output: null
Explanation: There is no in-order successor of the current node, so the answer is null.

 

Constraints:

  • The number of nodes in the tree is in the range [1, 104].
  • -105 <= Node.val <= 105
  • All Nodes will have unique values.

Solutions

Solution 1: Binary Search

The in-order traversal of a binary search tree is an ascending sequence, so we can use the binary search method.

The in-order successor node of a binary search tree node p satisfies:

  1. The value of the in-order successor node is greater than the value of node p.
  2. The in-order successor is the node with the smallest value among all nodes greater than p.

Therefore, for the current node root, if root.val > p.val, then root could be the in-order successor of p. We record root as ans and then search the left subtree, i.e., root = root.left. If root.val ≤ p.val, then root cannot be the in-order successor of p, and we search the right subtree, i.e., root = root.right.

The time complexity is O(h), where h is the height of the binary search tree. The space complexity is O(1).

PythonJavaC++GoTypeScriptJavaScript
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def inorderSuccessor(self, root: TreeNode, p: TreeNode) -> Optional[TreeNode]: ans = None while root: if root.val > p.val: ans = root root = root.left else: root = root.right return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !