Practice
res after the first iteration of the outer while loop completes?Solution
Step 1: Trace the first outer loop iteration
Initially, current_level contains only the root node with value 1.Step 2: Collect values and enqueue children
We pop node 1, append its value to level_nodes -> [1], and enqueue its children (3, 2, 4) into next_level.Final Answer:
Option A -> Option AQuick Check:
After first iteration, res = [[1]] as only root level processed [OK]
- Confusing first level with all children nodes
def levelOrderBottom(root):
levels = []
def dfs(node, level):
if not node:
return
if len(levels) == level:
levels.append([])
levels[level].append(node.val)
dfs(node.left, level + 1)
dfs(node.right, level + 1)
dfs(root, 0)
return levels[::-1]Solution
Step 1: Consider empty tree input (root = None)
If root is None, dfs returns immediately without adding levels.Step 2: Check what happens after dfs call
levels remains empty, so return levels[::-1] returns [], which is correct and expected.Step 3: Identify bug
Returning levels[::-1] when levels is empty is correct; the subtle bug is missing an explicit check for root being None before calling dfs to avoid unnecessary calls.Final Answer:
Option B -> Option BQuick Check:
Returning reversed empty list is correct; no bug in dfs call line [OK]
- Assuming dfs call on None causes error
- Not handling empty tree explicitly but no failure occurs
Solution
Step 1: Identify main operations
Each node is processed once (O(n)). For each node, insertion into ordered map (SortedDict) costs O(log k) where k is number of columns.Step 2: Combine complexities
Total time is O(n) * O(log k) = O(n log k). Sorting all nodes (O(n log n)) is avoided here.Final Answer:
Option C -> Option CQuick Check:
Ordered map insertion dominates, giving O(n log k) [OK]
- Assuming O(n) ignoring map insertion cost
- Confusing k (columns) with n (nodes) in complexity
Solution
Step 1: Identify number of node visits
Each node is pushed and popped exactly once from the stack, so O(n) visits.Step 2: Analyze max value update cost
Updating max_val is a constant time operation per node, no extra traversal per node.Final Answer:
Option C -> Option CQuick Check:
Linear traversal with constant work per node [OK]
- Assuming max_val tracking adds O(h) per node
- Confusing recursion stack space with time
- Thinking max_val comparisons cause O(n log n)
Solution
Step 1: Compare the buggy line with the correct logic
The correct connection is head.right.next = head.next.left, but here it uses head.next.right, which is incorrect.Step 2: Understand the impact
This causes right child's next pointer to point to the wrong node, breaking the chain.Final Answer:
Option D -> Option DQuick Check:
Right child's next must connect to next node's left child [OK]
- Confusing next.left and next.right
- Skipping null checks
- Not updating leftmost pointer
