Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #285: Inorder Successor in BST

In this guide, we solve Leetcode #285 Inorder Successor in BST in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

Given the root of a binary search tree and a node p in it, return the in-order successor of that node in the BST. If the given node has no in-order successor in the tree, return null.

Quick Facts

  • Difficulty: Medium
  • Premium: Yes
  • Tags: Tree, Depth-First Search, Binary Search Tree, Binary Tree

Intuition

We need to explore a structure deeply before backing up, which suits DFS.

DFS keeps local context on the call stack and is easy to implement recursively.

Approach

Define a recursive DFS that carries the necessary state.

Combine child results as the recursion unwinds.

Steps:

  • Define a recursive DFS with state.
  • Visit children and combine results.
  • Return the final aggregation.

Example

Input: root = [2,1,3], p = 1 Output: 2 Explanation: 1's in-order successor node is 2. Note that both p and the return value is of TreeNode type.

Python Solution

# 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]: ans = None while root: if root.val > p.val: ans = root root = root.left else: root = root.right return ans

Complexity

The time complexity is O(h)O(h)O(h), where hhh is the height of the binary search tree. The space complexity is O(1)O(1)O(1).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy