Prepin
Log in

Searching for the Successor in a Binary Search Tree

Approach / Explanation

This question requires you to develop an algorithm to locate the 'successor' in a Binary Search Tree (BST). The 'successor' is defined as the next-highest value corresponding to a specified node within the BST. Given a specific node in a BST, your task is to identify its successor. To effectively address this question, keep in mind to: Have a comprehensive understanding of the structure and workings of a Binary Search Tree (BST). Grasp the definition of a 'successor' in the context of a BST. Be capable of navigating and traversing a BST. Get accustomed to writing recursive algorithms, which are typically required for operations involving BSTs.

Suggested Answer

Here's a straightforward algorithm to determine the successor of a node in a binary search tree (BST): def successorBST(root, targetNode): # If the targetNode has a right child, the successor is the smallest value in the right subtree if targetNode.right is not None: return findMinValue(targetNode.right) # If there is no right child, the successor is one of the ancestors. We traverse from the root. successor = None while root: if targetNode.value < root.value: successor = root root = root.left elif targetNode.value > root.value: root = root.right else: break return successor In this algorithm, the findMinValue function simply traverses down to the leftmost leaf, which will contain the smallest value in the tree or subtree.

Alternative Answer

Below is a recursive method to determine the successor. def successorBST(node, targetNode): if node is None: return None if node.data This method employs a conventional binary search to find the node. We also continuously pass and update the potential successor based on the properties of the BST (i.e., each time we move to the left, we set the successor to the current node). Consequently, when we reach the target node, we will have already updated its successor.

Question Details

Difficulty & Category

Medium
algorithms

Product

AI Candidate AgentCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin | All rights reserved.