Practice
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
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]
root = TreeNode(3)
root.left = TreeNode(9)
root.right = TreeNode(20, TreeNode(15), TreeNode(7))
print(levelOrderBottom(root))Solution
Step 1: Trace dfs calls and levels
Level 0: [3], Level 1: [9, 20], Level 2: [15, 7]Step 2: Reverse levels list before returning
Reversing [[3], [9, 20], [15, 7]] yields [[15, 7], [9, 20], [3]]Final Answer:
Option A -> Option AQuick Check:
Output matches bottom-up level order traversal [OK]
- Forgetting to reverse levels
- Mixing up left and right children order
from collections import deque
from sortedcontainers import SortedDict
def verticalOrder(root):
if not root:
return []
col_table = SortedDict()
queue = deque([(root, 0)])
while queue:
node, col = queue.popleft()
if col not in col_table:
col_table[col] = []
col_table[col].append(node.val)
if node.left:
queue.append((node.left, col - 1))
if node.right:
queue.append((node.right, col + 1))
return list(col_table.values())
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
root = TreeNode(3, TreeNode(9), TreeNode(20, TreeNode(15), TreeNode(7)))
print(verticalOrder(root))What is the output of this code?Solution
Step 1: Trace queue and col_table updates
Start with root (3, col=0). Append 3 to col 0. Enqueue left child (9, col=-1), right child (20, col=1).Step 2: Process nodes in BFS order
Process (9, -1): append 9 to col -1. No children. Process (20, 1): append 20 to col 1. Enqueue (15, 0), (7, 2). Process (15, 0): append 15 to col 0. Process (7, 2): append 7 to col 2.Final Answer:
Option A -> Option AQuick Check:
Columns sorted: -1:[9], 0:[3,15], 1:[20], 2:[7] matches [[9], [3, 15], [20], [7]] [OK]
- Mixing order of nodes in same column
- Misassigning column indices for children
Solution
Step 1: Understand the problem constraints
The width includes null nodes between end-nodes, so counting only non-null nodes per level underestimates width.Step 2: Identify the approach that tracks positions
BFS with indexing assigns position indices to nodes, allowing calculation of width as the difference between first and last indices at each level. Normalizing indices prevents integer overflow on deep trees.Final Answer:
Option A -> Option AQuick Check:
Indexing with normalization handles sparse trees and deep levels correctly [OK]
- Counting only non-null nodes per level
- Using DFS without proper indexing
- Ignoring index normalization causing overflow
def rightSideView(root: Optional[TreeNode]) -> List[int]:
rightside = []
def dfs(node, depth):
if not node:
return
if depth == len(rightside):
rightside.append(node.val)
dfs(node.left, depth + 1) # Line X
dfs(node.right, depth + 1) # Line Y
dfs(root, 0)
return rightside
Which line contains the bug causing incorrect right side view?Solution
Step 1: Understand traversal order
The code visits left child before right child, so left nodes are appended first at each depth.Step 2: Why this causes bug
Visiting left first causes left nodes to be recorded as visible, overwriting right nodes that should be visible from the right side.Final Answer:
Option B -> Option BQuick Check:
Swapping left and right child calls fixes the bug [OK]
- Visiting left child before right in DFS causes wrong nodes appended
- Appending nodes without checking depth length
- Not handling null nodes properly
Solution
Step 1: Understand requirement to return only k bottom-most levels
We must know total depth to identify bottom k levels.Step 2: Evaluate options
Only performing full DFS and then slicing the reversed levels guarantees correctness; pruning by depth is incorrect because bottom levels are deepest, not shallowest.Final Answer:
Option D -> Option DQuick Check:
Full DFS then slicing is simple and correct [OK]
- Pruning DFS early loses bottom levels
- Inserting at front of level list breaks order
