Bird
Raised Fist0
Interview Prepbinary-search-treesmediumAmazonGoogle

Trim a BST

Choose your preparation mode4 modes available
▶
Steps
setup

Initialize root and parameters

The initial BST is constructed with root value 3, and the range [1,3] is set. No pruning has started yet.

💡 Setting up the tree and range is essential before pruning begins.
Line:root = TreeNode(3) root.left = TreeNode(0) root.right = TreeNode(4) low, high = 1, 3
💡 The tree structure and range are now ready for trimming.
📊
Trim a BST - Watch the Algorithm Execute, Step by Step
Watching each pointer move and subtree adjustment helps you understand how BST properties enable efficient pruning without recursion.
Step 1/11
·Active fill★Answer cell
Current node: 0
30421
Current node: 0
30421
Current node: 0
30421
DFS Stack
0 (entered)cur=0
Current node: 0
30421
DFS Stack
0 (left_done)cur=0
Current node: 3
30421
DFS Stack
0 (left_done)cur=3
Current node: 3
30421
DFS Stack
0 (left_done)cur=3
Current node: 4
30421
DFS Stack
0 (left_done)cur=4
Current node: 0
30421
DFS Stack
0 (right_entered)cur=0
Current node: 0
30421
DFS Stack
0 (right_done)cur=0
Current node: 4
30421
DFS Stack
0 (right_done)cur=4
Current node: 0
32104
Return: 0

Key Takeaways

✓ The root is first moved to a valid node within the range before any pruning.

This step ensures the trimmed tree's root is always valid, which is not obvious from code alone.

✓ Left subtree pruning removes nodes less than low by adjusting left pointers iteratively.

Seeing pointer updates visually clarifies how pruning avoids recursion and preserves BST structure.

✓ Right subtree pruning removes nodes greater than high similarly by adjusting right pointers.

The symmetry of left and right pruning is easier to grasp when watching each pointer move.

Practice

(1/5)
1. Consider the following code snippet for searching a value in a BST. What will be printed when searching for the value 3 in the given tree?
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def searchBST(root, val):
    current = root
    while current:
        if current.val == val:
            return current
        elif val < current.val:
            current = current.left
        else:
            current = current.right
    return None

root = TreeNode(4, TreeNode(2, TreeNode(1), TreeNode(3)), TreeNode(7))
result = searchBST(root, 3)
print(result.val if result else 'null')
easy
A. 2
B. 7
C. null
D. 3

Solution

  1. Step 1: Trace the search path

    Start at root (4). Since 3 < 4, move to left child (2). Since 3 > 2, move to right child (3).
  2. Step 2: Check node value

    Current node value is 3, which matches the search value, so return this node.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Search follows BST property correctly and finds node with value 3 [OK]
Hint: Follow BST property to move left or right [OK]
Common Mistakes:
  • Returning wrong node value due to off-by-one traversal
2. What is the average time complexity per call of next() in the Morris traversal based BST Iterator, assuming the BST has n nodes?
medium
A. O(1) amortized per next() call because each edge is visited at most twice.
B. O(n) per next() call because each call may traverse the entire tree.
C. O(h) per next() call where h is the tree height due to traversing left children.
D. O(log n) per next() call assuming a balanced BST and stack usage.

Solution

  1. Step 1: Understand Morris traversal edge visits

    Each edge in the BST is visited at most twice: once to create a thread and once to remove it.
  2. Step 2: Calculate amortized cost per next()

    Since total work is O(n) for n nodes, and there are n calls to next(), average cost per call is O(1) amortized.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Amortized O(1) per next() matches Morris traversal properties [OK]
Hint: Morris traversal visits edges twice total [OK]
Common Mistakes:
  • Assuming worst-case O(n) per call
  • Confusing with stack-based O(h)
  • Ignoring amortized analysis
3. The following code attempts to convert a BST to a Greater Tree using reverse inorder traversal. Identify the line that contains a subtle bug causing incorrect node values.
medium
A. Line 8: node = node.left instead of node = node.right
B. Line 6: while node: loop condition
C. Line 10: acc_sum += node.val accumulation
D. Line 12: node = node.right traversal after updating node

Solution

  1. Step 1: Understand traversal order needed

    Reverse inorder traversal requires visiting right subtree first to accumulate greater values.
  2. Step 2: Identify incorrect subtree traversal

    Line 8 incorrectly moves to left child first, reversing traversal order and causing wrong sums.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Changing node = node.left to node = node.right fixes traversal order [OK]
Hint: Reverse inorder must traverse right subtree first [OK]
Common Mistakes:
  • Swapping left and right subtree traversal order
  • Resetting acc_sum inside loops
  • Updating node values before traversing right subtree
4. What is the worst-case time complexity of the optimized iterative DFS with BST pruning approach for computing the range sum of a BST with n nodes and height h?
medium
A. O(h) because only nodes along the height are visited
B. O(log n) because pruning skips most nodes
C. O(n) because in worst case pruning does not skip any nodes
D. O(n log n) because each node may be visited multiple times due to stack operations

Solution

  1. Step 1: Identify worst-case scenario

    Worst case occurs when all nodes fall within the range or pruning is ineffective, so all n nodes are visited.
  2. Step 2: Analyze time complexity

    Each node is processed once, so time complexity is O(n). Stack operations are O(1) amortized per node.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Worst case is full traversal, O(n) time [OK]
Hint: Worst case equals full traversal of all nodes [OK]
Common Mistakes:
  • Assuming pruning always reduces to O(log n)
  • Confusing height h with number of nodes n
5. Suppose the BST validation problem is modified so that duplicate values are allowed only on the right subtree (i.e., node values in the right subtree can be equal to the current node). Which modification to the inorder traversal check correctly validates this variant?
hard
A. Change the comparison to node.val < prev[0] to allow duplicates on the right subtree.
B. Change the comparison to node.val < prev[0] for all nodes except when node is right child, then allow node.val == prev[0].
C. Change the comparison to node.val <= prev[0] to allow duplicates anywhere.
D. Change the comparison to node.val < prev[0] only when traversing left subtree, and node.val <= prev[0] when traversing right subtree.

Solution

  1. Step 1: Understand variant allowing duplicates only on right subtree

    Duplicates allowed only if they appear in right subtree, so inorder sequence can have equal values only when moving right.
  2. Step 2: Modify comparison accordingly

    During inorder traversal, allow node.val == prev[0] only if current node is right child of previous node; otherwise, enforce strict inequality.
  3. Step 3: Reason why other options fail

    Change the comparison to node.val < prev[0] to allow duplicates on the right subtree. allows duplicates anywhere; Change the comparison to node.val <= prev[0] to allow duplicates anywhere. allows duplicates anywhere; Change the comparison to node.val < prev[0] only when traversing left subtree, and node.val <= prev[0] when traversing right subtree. is ambiguous and not implementable in simple inorder traversal without parent info.
  4. Final Answer:

    Option B -> Option B
  5. Quick Check:

    Allow duplicates only on right subtree requires conditional equality check [OK]
Hint: Duplicates allowed only on right subtree require conditional comparison [OK]
Common Mistakes:
  • Allowing duplicates anywhere
  • Ignoring subtree direction in comparison
  • Using simple <= everywhere
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