VOOZH about

URL: https://www.geeksforgeeks.org/dsa/inorder-predecessor-successor-given-key-bst/

⇱ Inorder predecessor and successor in BST - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Inorder predecessor and successor in BST

Last Updated : 8 Mar, 2026

Given the root of a Binary Search Tree (BST) and an integer key, find the predecessor and successor of the given key.

  • The predecessor of a node is the node with the largest value smaller than the key.
  • The successor of a node is the node with the smallest value greater than the key.

If the predecessor does not exist, return NULL for the predecessor. If the successor does not exist, return NULL for the successor.

Note: The given key may or may not be present in the BST.

Examples:

Input: key = 65

👁 420046821

Output: [60, 70]
Explanation: In given BST the inorder predecessor of 65 is 60 and inorder successor of 65 is 70.

👁 12

Input: key = 8

👁 frame_34

Output: [4, 9]
Explanation: In the given BST the inorder predecessor of 8 is 4 and inorder successor of 8 is 9.

👁 frame_3141

[Naive Approach] Maintaining predecessor and successors - O(n) Time and O(1) Space

We traverse the tree and maintain two values for predecessor and successors and compare the current node's value with both of them.

  • Traverse the tree and keep track of predecessor and successor values.
  • If predecessor < node.data < key, update the predecessor. If successor > node.data > key, update the successor.

Output
60 70

[Expected Approach-1] Using Two Traversals - O(h) Time and O(1) Space

We traverse the tree twice — once to find the predecessor and once to find the successor.

For predecessor ,

  • if root < key, then root becomes the predecessor and we search for larger value.
  • if root >= key, then as predecessor < key, therefore we search in left subtree.

For successor,

  • if root <= key, then as successor > key, therefore we search in right subtree.
  • if root > key, and then root becomes the successor and we search for smaller value.

Output
60 70

[Expected Approach-2] Using Single Traversal - O(h) Time and O(1) Space

The idea is to traverse the BST once to find both the predecessor and successor of a given key.

  • If node < key, it can be the predecessor, so move to the right subtree to find a larger value still < key.
  • If node > key, it can be the successor, so move to the left subtree to find a smaller value still > key.
  • If node = key, predecessor is the maximum in left subtree and successor is the minimum in right subtree.

Output
60 70
Comment