Inorder successor and predecessor in BST

Binary Search Trees Medium Medium

Given the root node of a binary search tree (BST) and an integer key. Return the Inorder predecessor and successor of the given key from the provided BST.


If predecessor or successor is missing then return -1.

Examples:

Input : root = [5, 2, 10, 1, 4, 7, 12] , key = 10

Output : [7, 12]

Explanation :

Input : root = [5, 2, 10, 1, 4, 7, 12] , key = 12

Output : [10, -1]

Explanation :

Input : root = [5, 2, 10, 1, 4, 7, 12] , key = 1

Constraints

  • 1 <= Number of Nodes <= 104
  • 1 <= Node.val <= 105
  • All the values Node.val are unique.

Hints

  • "If key exists in the BST and has a left subtree, the predecessor is the rightmost (max) node in its left subtree. Otherwise, traverse the BST: If root.val < key, update predecessor = root.val and move right. Otherwise, move left."
  • "If key exists and has a right subtree, the successor is the leftmost (min) node in its right subtree. Otherwise, traverse the BST: If root.val > key, update successor = root.val and move left. Otherwise, move right."

Company Tags

Visa Ernst & Young Wayfair Unity Technologies Boston Consulting Group Morgan Stanley NVIDIA Robinhood Ubisoft ARM MongoDB Alibaba Epic Games Electronic Arts Philips Healthcare Lyft Qualcomm OYO Rooms HashiCorp Deloitte Teladoc Health Bungie Zynga Snowflake Salesforce Google Microsoft Amazon Meta Apple Netflix Adobe