Inorder successor and predecessor in BST

Binary Search Trees Medium Medium
  • Fun Fact: The problem of finding Inorder predecessor and successor in a Binary Search Tree (BST) can be seen in many real-world applications such as databases or software that deal with a large set of sorted data, allowing quick insertion, deletion and lookup operations
  • For instance, popular database management systems like Oracle or MySQL use varieties of tree data structures such as B-Tree, B+ Tree (an extension of BST)
  • When you need to find nearest lesser (predecessor) and nearest greater (successor) values to a particular key, applications can use Inorder traversal method, similar to the above mentioned problem, within such tree-based structures to get the result efficiently
  • It's a common operation, particularly in navigating, organizing and managing hierarchical or ordered information

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