class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def __init__(self):
self.index = 0
def helper(self, nums, left, right):
# STEP 1-20: Recursive helper to build BST
if left > right:
return None # STEP 5,9,15,19 base case
mid = (left + right) // 2 # STEP 2,4,8,14,18 mid calculation
left_child = self.helper(nums, left, mid - 1) # STEP 3,5,7,9,15,19 recurse left
root = TreeNode(nums[mid]) # STEP 6,10,12,16,20 create node
self.index += 1 # STEP 6,10,12,16,20 increment index
root.left = left_child # STEP 12 attach left
root.right = self.helper(nums, mid + 1, right) # STEP 7,13,17 recurse right
return root # STEP 11,20 return node
def sorted_array_to_bst(self, nums):
self.index = 0 # STEP 1 initialize
return self.helper(nums, 0, len(nums) - 1) # STEP 1 start recursion
if __name__ == '__main__':
nums = [-10, -3, 0, 5, 9]
sol = Solution()
root = sol.sorted_array_to_bst(nums)
def inorder(node):
return inorder(node.left) + [node.val] + inorder(node.right) if node else []
print(inorder(root))
📊
Convert Sorted Array to Height-Balanced BST - Watch the Algorithm Execute, Step by Step
Watching each recursive call and node creation helps you understand how the algorithm balances the tree by choosing midpoints and how recursion unwinds to assemble the final BST.
✓ Choosing the middle element as root at each recursive step ensures the BST is height-balanced.
This insight is hard to see from code alone but clear when watching the recursive splits and node creations.
✓ The recursion builds left subtree first, then root, then right subtree, which is crucial for correct BST construction.
Understanding the order of recursion helps grasp how the tree nodes are linked properly.
✓ Base cases where left > right stop recursion and return None, marking leaf nodes' children.
Visualizing base cases clarifies when recursion ends and how leaf nodes are formed.
Practice
(1/5)
1. Consider the following Python code snippet for balancing a BST using inorder traversal and iterative construction. Given the BST with nodes 1, 2, 3 inserted in that order, what is the value of the root node after balancing?
easy
A. 1
B. 2
C. 3
D. None (empty tree)
Solution
Step 1: Perform inorder traversal on BST with nodes 1, 2, 3
Inorder traversal yields nodes in sorted order: [1, 2, 3].
Middle index is 1 (0-based), so node with value 2 becomes root.
Final Answer:
Option B -> Option B
Quick Check:
Middle of [1,2,3] is 2 -> root value 2 [OK]
Hint: Middle element of sorted nodes becomes root [OK]
Common Mistakes:
Choosing left or right middle always, skewing tree
Confusing preorder with inorder traversal results
Forgetting to reset left/right pointers causing cycles
2. Consider the following Python code implementing BST validation using inorder traversal. What is the output of the program when run with the given test cases?
easy
A. true followed by false
B. true followed by true
C. false followed by true
D. false followed by false
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)
First tree valid BST, second invalid due to subtree violation [OK]
Hint: Inorder traversal must be strictly increasing [OK]
Common Mistakes:
Assuming subtree root comparison is enough
Confusing output order
Missing strict inequality check
3. What is the time complexity of balancing a BST using the optimal approach of inorder traversal followed by iterative balanced BST construction from the collected nodes?
medium
A. O(n log n) due to sorting nodes during traversal
B. O(n) because inorder traversal and balanced rebuild each take linear time
C. O(n^2) because rebuilding the tree involves repeated subtree constructions
D. O(n) for traversal but O(n log n) for balanced tree construction
Solution
Step 1: Analyze inorder traversal time
Inorder traversal visits each node once -> O(n).
Step 2: Analyze balanced BST construction time
Rebuilding uses indices to pick middle nodes without extra sorting -> O(n).
Step 3: Consider sorting complexity
Although inorder traversal produces sorted nodes, if sorting is mistakenly applied, complexity becomes O(n log n).
Final Answer:
Option A -> Option A
Quick Check:
Sorting nodes during traversal leads to O(n log n) [Trap]
Hint: Beware of sorting overhead; if sorting is done, complexity is O(n log n)
Common Mistakes:
Assuming sorting is not needed, leading to O(n)
Thinking recursive rebuild is O(n^2) due to repeated subtree calls
Confusing traversal and construction complexities
4. What is the time complexity of the iterative inorder traversal approach to find the kth smallest element in a BST, where H is the height of the tree and k is the input parameter?
medium
A. O(H + k), where H is the height of the tree and k is the kth element to find
B. O(k), since only k nodes are visited
C. O(k log n), assuming balanced BST
D. O(n), where n is the total number of nodes in the BST
Solution
Step 1: Analyze traversal steps
The algorithm traverses down to the leftmost node (cost O(H)) and then visits k nodes in inorder sequence.
Step 2: Combine costs
Total time is O(H) to reach leftmost node plus O(k) to visit k nodes, so O(H + k).
Final Answer:
Option A -> Option A
Quick Check:
Traversal cost depends on height plus k nodes visited [OK]
Hint: Traversal cost includes height plus k nodes visited [OK]
Common Mistakes:
Assuming O(n) always
Ignoring height cost
Assuming only k nodes visited without stack overhead
5. 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
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.
Step 2: Analyze time complexity
Each node is processed once, so time complexity is O(n). Stack operations are O(1) amortized per node.
Final Answer:
Option C -> Option C
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
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.