Bird
Raised Fist0
DSA Rustprogramming

BST Inorder Successor in DSA Rust

Choose your learning style10 modes available
Mental Model
The inorder successor of a node in a BST is the next node in sorted order. It is the smallest node larger than the given node.
Analogy: Imagine a line of people sorted by height. The inorder successor is the person just taller than you standing next in line.
      5
     / \
    3   7
   / \   \
  2   4   8
↑node=3
Dry Run Walkthrough
Input: BST: 5 -> 3 -> 7 -> 2 -> 4 -> 8, find inorder successor of node 3
Goal: Find the node that comes right after 3 in sorted order
Step 1: Check if node 3 has right child
      5
     / \
    3 -> 7
   / \   \
  2   4   8
↑node=3
Why: If right child exists, successor is smallest node in right subtree
Step 2: Go to right child 4 and find its leftmost child
      5
     / \
    3   7
   / \   \
  2  [4]  8
↑node=3
Why: 4 has no left child, so 4 is successor
Step 3: Return node 4 as successor
Successor = 4
Why: 4 is the smallest node greater than 3
Result:
4
Annotated Code
DSA Rust
use std::rc::Rc;
use std::cell::RefCell;

#[derive(Debug, Clone)]
struct TreeNode {
    val: i32,
    left: Option<Rc<RefCell<TreeNode>>>,
    right: Option<Rc<RefCell<TreeNode>>>,
}

impl TreeNode {
    fn new(val: i32) -> Rc<RefCell<TreeNode>> {
        Rc::new(RefCell::new(TreeNode { val, left: None, right: None }))
    }
}

fn inorder_successor(root: Option<Rc<RefCell<TreeNode>>>, p: Rc<RefCell<TreeNode>>) -> Option<Rc<RefCell<TreeNode>>> {
    // If p has right child, successor is leftmost node in right subtree
    if let Some(right) = p.borrow().right.clone() {
        let mut curr = right;
        while let Some(left) = curr.borrow().left.clone() {
            curr = left; // advance to leftmost node
        }
        return Some(curr);
    }
    // Otherwise, successor is ancestor where p is in left subtree
    let mut successor = None;
    let mut curr = root;
    while let Some(node) = curr {
        if p.borrow().val < node.borrow().val {
            successor = Some(node.clone()); // potential successor
            curr = node.borrow().left.clone(); // go left
        } else if p.borrow().val > node.borrow().val {
            curr = node.borrow().right.clone(); // go right
        } else {
            break; // found p
        }
    }
    successor
}

fn main() {
    // Build BST
    let root = TreeNode::new(5);
    let node3 = TreeNode::new(3);
    let node7 = TreeNode::new(7);
    let node2 = TreeNode::new(2);
    let node4 = TreeNode::new(4);
    let node8 = TreeNode::new(8);

    root.borrow_mut().left = Some(node3.clone());
    root.borrow_mut().right = Some(node7.clone());
    node3.borrow_mut().left = Some(node2.clone());
    node3.borrow_mut().right = Some(node4.clone());
    node7.borrow_mut().right = Some(node8.clone());

    // Find inorder successor of node 3
    if let Some(succ) = inorder_successor(Some(root.clone()), node3.clone()) {
        println!("{}", succ.borrow().val);
    } else {
        println!("No successor");
    }
}
if let Some(right) = p.borrow().right.clone() {
check if node p has right subtree
while let Some(left) = curr.borrow().left.clone() {
find leftmost node in right subtree
return Some(curr);
return leftmost node as successor
while let Some(node) = curr {
traverse from root to find successor ancestor
if p.borrow().val < node.borrow().val {
go left and update successor candidate
else if p.borrow().val > node.borrow().val {
go right, no successor update
else { break; }
found node p, stop traversal
OutputSuccess
4
Complexity Analysis
Time: O(h) because we traverse down the tree height h at most twice
Space: O(1) because we use only a few pointers, no extra data structures
vs Alternative: Naive approach does inorder traversal O(n) to find successor, this uses BST property to do it in O(h)
Edge Cases
Node has no right child and is the largest node
No successor found, returns None
DSA Rust
while let Some(node) = curr {
Node has right child with no left subtree
Successor is immediate right child
DSA Rust
if let Some(right) = p.borrow().right.clone() {
Node is root with right subtree
Successor found in right subtree
DSA Rust
while let Some(left) = curr.borrow().left.clone() {
When to Use This Pattern
When asked for the next bigger element in a BST, use the inorder successor pattern to find the smallest node larger than the given node efficiently.
Common Mistakes
Mistake: Not checking if the node has a right subtree first
Fix: Always check right subtree first because successor is leftmost node there if it exists
Mistake: Not updating successor candidate when moving left from root
Fix: Update successor candidate when moving left to keep track of possible successor
Summary
Finds the next node in sorted order after a given node in a BST.
Use when you need the immediate larger value than a node in a BST.
If right child exists, successor is leftmost node in right subtree; else, successor is ancestor where node is in left subtree.

Practice

(1/5)
1. What is the inorder successor of a node in a Binary Search Tree (BST)?
easy
A. The node with the smallest key greater than the given node's key
B. The node with the largest key smaller than the given node's key
C. The left child of the given node
D. The right child of the given node

Solution

  1. Step 1: Understand inorder traversal order

    Inorder traversal visits nodes in ascending order of their keys in a BST.
  2. Step 2: Define inorder successor

    The inorder successor of a node is the next node visited after it in inorder traversal, which means the smallest node with a key greater than the current node.
  3. Final Answer:

    The node with the smallest key greater than the given node's key -> Option A
  4. Quick Check:

    Inorder successor = next bigger node [OK]
Hint: Inorder successor is next bigger node in sorted order [OK]
Common Mistakes:
  • Confusing successor with predecessor
  • Thinking successor is always right child
  • Ignoring BST property in definition
2. Which Rust function signature correctly represents a method to find the inorder successor of a BST node?
easy
A. fn inorder_successor(root: &Option, p: &TreeNode) -> Option<&TreeNode>
B. fn inorder_successor(root: TreeNode, p: TreeNode) -> TreeNode
C. fn inorder_successor(root: &mut TreeNode, p: &mut TreeNode) -> TreeNode
D. fn inorder_successor(root: Option<TreeNode>, p: Option<TreeNode>) -> Option<TreeNode>

Solution

  1. Step 1: Understand Rust ownership and references

    BST nodes are usually wrapped in Option to allow null and heap allocation. Passing references avoids ownership transfer.
  2. Step 2: Analyze function signature correctness

    Option<&TreeNode> as return type allows returning a reference to a node or None. Input parameters as references to avoid moving ownership.
  3. Final Answer:

    fn inorder_successor(root: &Option, p: &TreeNode) -> Option<&TreeNode> -> Option A
  4. Quick Check:

    Use references and Option for safe BST traversal [OK]
Hint: Use references and Option types for BST nodes in Rust [OK]
Common Mistakes:
  • Passing nodes by value causing ownership errors
  • Returning owned nodes instead of references
  • Using mutable references unnecessarily
3. Given the following Rust code snippet for finding the inorder successor, what will be printed?
struct TreeNode {
    val: i32,
    left: Option,
    right: Option,
}

fn inorder_successor(root: &Option, p_val: i32) -> Option<i32> {
    let mut successor = None;
    let mut current = root;
    while let Some(node) = current {
        if p_val < node.val {
            successor = Some(node.val);
            current = &node.left;
        } else {
            current = &node.right;
        }
    }
    successor
}

fn main() {
    let root = Some(Box::new(TreeNode {
        val: 20,
        left: Some(Box::new(TreeNode {
            val: 10,
            left: None,
            right: Some(Box::new(TreeNode {
                val: 15,
                left: None,
                right: None,
            })),
        })),
        right: Some(Box::new(TreeNode {
            val: 30,
            left: None,
            right: None,
        })),
    }));
    let result = inorder_successor(&root, 15);
    println!("{:?}", result);
}
medium
A. None
B. Some(20)
C. Some(15)
D. Some(30)

Solution

  1. Step 1: Trace the search for successor of node with value 15

    Start at root (20). Since 15 < 20, successor = 20, move left to node 10. 15 > 10, move right to node 15.
  2. Step 2: Continue traversal and finalize successor

    At node 15, 15 == 15, move right which is None. Loop ends. Last successor recorded is 20.
  3. Final Answer:

    Some(20) -> Option B
  4. Quick Check:

    Next bigger than 15 is 20 [OK]
Hint: Successor is smallest bigger node found going left [OK]
Common Mistakes:
  • Returning the node itself as successor
  • Confusing left and right subtree traversal
  • Not updating successor when moving left
4. The following Rust function aims to find the inorder successor of a node in a BST but has a bug. What is the bug?
fn inorder_successor(root: &Option, p_val: i32) -> Option<i32> {
    let mut successor = None;
    let mut current = root;
    while let Some(node) = current {
        if p_val <= node.val {
            successor = Some(node.val);
            current = &node.left;
        } else {
            current = &node.right;
        }
    }
    successor
}
medium
A. Not handling None case for root
B. Function returns value instead of reference
C. Successor should be updated only when p_val > node.val
D. Using <= instead of < causes incorrect successor when p_val equals node.val

Solution

  1. Step 1: Analyze condition p_val <= node.val

    Using <= means successor updates even when p_val equals node.val, which incorrectly sets successor to the node itself.
  2. Step 2: Correct condition for successor update

    Successor should update only when p_val < node.val to find the next bigger node, not the node itself.
  3. Final Answer:

    Using <= instead of < causes incorrect successor when p_val equals node.val -> Option D
  4. Quick Check:

    Use < for successor update, not <= [OK]
Hint: Use strict less than (<) to avoid self as successor [OK]
Common Mistakes:
  • Confusing < and <= in comparisons
  • Ignoring edge case when p_val equals node.val
  • Not testing with equal values
5. You have a BST where each node has a parent pointer in addition to left and right children. How can you find the inorder successor of a given node p efficiently using this extra pointer?
hard
A. Successor is always the right child of p
B. Always go to the root and perform inorder traversal to find successor
C. If p has right child, successor is leftmost node in right subtree; else go up using parent until node is left child
D. Use a stack to store nodes and pop until successor is found

Solution

  1. Step 1: Check if node has right subtree

    If p has a right child, the successor is the leftmost node in that right subtree.
  2. Step 2: If no right child, use parent pointer

    Move up the tree using parent pointers until you find a node which is the left child of its parent; that parent is the successor.
  3. Final Answer:

    If p has right child, successor is leftmost node in right subtree; else go up using parent until node is left child -> Option C
  4. Quick Check:

    Use right subtree or climb parents to find successor [OK]
Hint: Use parent pointer to climb up when no right child [OK]
Common Mistakes:
  • Ignoring parent pointer advantage
  • Assuming successor is always right child
  • Performing full traversal unnecessarily
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard