KatInterview

285. Inorder Successor in BST

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the in-order successor of a given node p in a Binary Search Tree (BST). The in-order successor is the node that would appear immediately after p in an in-order traversal of the tree. Since an in-order traversal of a BST visits nodes in ascending order of their values, the in-order successor is the node with the smallest value that is strictly greater than p.val.

Solution

Inorder Successor in BST in Python

# 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]':
        successor = None
        
        # Start traversing from the root
        current = root
        while current:
            # If p's value is smaller than the current node's value,
            # this node is a potential successor. Record it and move
            # to the left to find a potentially smaller successor.
            if p.val < current.val:
                successor = current
                current = current.left
            else:
                # If p's value is greater than or equal to the current node's value,
                # this node cannot be the successor. The successor must be
                # in the right subtree.
                current = current.right
        
        return successor

Inorder Successor in BST in Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        TreeNode successor = null;
        
        // Start traversing from the root
        TreeNode current = root;
        while (current != null) {
            // If p's value is smaller than the current node's value,
            // this node is a potential successor. Record it and move
            // to the left to find a potentially smaller successor.
            if (p.val < current.val) {
                successor = current;
                current = current.left;
            } else {
                // If p's value is greater than or equal to the current node's value,
                // this node cannot be the successor. The successor must be
                // in the right subtree.
                current = current.right;
            }
        }
        
        return successor;
    }
}

Inorder Successor in BST in C++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
        TreeNode* successor = nullptr;
        
        // Start traversing from the root
        while (root != nullptr) {
            // If p's value is smaller than the current node's value,
            // this node is a potential successor. Record it and move
            // to the left to find a potentially smaller successor.
            if (p->val < root->val) {
                successor = root;
                root = root->left;
            } else {
                // If p's value is greater than or equal to the current node's value,
                // this node cannot be the successor. The successor must be
                // in the right subtree.
                root = root->right;
            }
        }
        
        return successor;
    }
};

Inorder Successor in BST in TypeScript

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function inorderSuccessor(root: TreeNode | null, p: TreeNode | null): TreeNode | null {
	// The problem statement implies p is a non-null node in the tree.
    // If p could be null, we might need to handle it, e.g., by returning null.
    if (!p) {
        return null;
    }

    let successor: TreeNode | null = null;
    let current: TreeNode | null = root;

    while (current) {
        // If p's value is smaller than the current node's value,
        // this node is a potential successor. Record it and move
        // to the left to find a potentially smaller successor.
        if (p.val < current.val) {
            successor = current;
            current = current.left;
        } else {
            // If p's value is greater than or equal to the current node's value,
            // this node cannot be the successor. The successor must be
            // in the right subtree.
            current = current.right;
        }
    }

    return successor;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.