Practice
Solution
Step 1: Understand BST property
The BST property requires all left subtree nodes to be less than the current node and all right subtree nodes to be greater, strictly increasing in inorder traversal.Step 2: Recognize inorder traversal pattern
Inorder traversal of a valid BST produces a strictly increasing sequence of values, so verifying this sequence guarantees correctness efficiently.Final Answer:
Option D -> Option DQuick Check:
Inorder traversal yields sorted values for BST [OK]
- Only comparing node with immediate children
- Using greedy checks without global ordering
- Confusing subtree min/max with inorder sequence
Solution
Step 1: Trace first tree (2,1,3)
Inorder traversal yields [1,2,3], strictly increasing, so returns true.Step 2: Trace second tree (5,1,4 with children 3 and 6)
Inorder traversal yields [1,5,3,4,6], 3 < 5 violates BST property, so returns false.Final Answer:
Option A -> Option AQuick Check:
First tree valid BST, second invalid due to subtree violation [OK]
- Assuming subtree root comparison is enough
- Confusing output order
- Missing strict inequality check
next() in the Morris traversal based BST Iterator, assuming the BST has n nodes?Solution
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.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.Final Answer:
Option A -> Option AQuick Check:
Amortized O(1) per next() matches Morris traversal properties [OK]
- Assuming worst-case O(n) per call
- Confusing with stack-based O(h)
- Ignoring amortized analysis
Solution
Step 1: Identify height-based operations
Deletion involves searching down the tree (O(h)) and finding the in-order successor, which is also O(h) in worst case.Step 2: Combine operations and recursion
Successor search and recursive deletion happen along a path of length h, so total time is O(h), not O(h^2).Final Answer:
Option A -> Option AQuick Check:
Time proportional to tree height, not total nodes or squared height [OK]
- Assuming balanced BST always (log n)
- Confusing recursion depth with squared complexity
- Thinking successor search adds extra factor
Solution
Step 1: Identify time complexity
The algorithm visits each node exactly once in inorder traversal, so time is O(n).Step 2: Identify space complexity
Space is O(h) due to recursion stack, where h is the height of the tree; no extra arrays store all nodes.Final Answer:
Option A -> Option AQuick Check:
Linear time and stack space proportional to tree height [OK]
- Confusing recursion stack space with storing all nodes
- Assuming O(n log n) due to sorting
- Ignoring recursion stack space
