Hint: Pick last node at each level during BFS [OK]
Common Mistakes:
Choosing leftmost nodes instead of rightmost
Mixing node values from different levels
Ignoring null children in traversal
4. Identify the bug in this TypeScript code for right side view and select the fix.
function rightSideView(root: TreeNode | null): number[] {
const result: number[] = [];
if (!root) return result;
const queue: TreeNode[] = [root];
while (queue.length) {
const size = queue.length;
for (let i = 0; i < size; i++) {
const node = queue.shift();
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
if (i === size - 1) result.push(node.val);
}
}
return result;
}
medium
A. Initialize queue as empty array instead of [root]
B. Change queue type to (TreeNode | undefined)[] and check node is not undefined after shift
C. Remove the if condition checking i === size - 1
D. Push left child after right child in the queue
Solution
Step 1: Analyze queue.shift() return type
queue.shift() can return undefined if queue is empty, but here size ensures it's not empty. Still, TypeScript requires checking.
Step 2: Fix type safety
Change queue type to allow undefined and check node is not undefined before accessing properties.
Final Answer:
Change queue type and check node after shift -> Option B
Quick Check:
Type safety requires checking shift result [OK]
Hint: Check shift() result for undefined before use [OK]
Common Mistakes:
Ignoring possible undefined from shift()
Removing correct condition for rightmost node
Changing queue initialization incorrectly
5. You want to find the right side view of a binary tree but only have access to a preorder traversal array with nulls for missing nodes, e.g., [1, 2, null, 5, null, null, 3, null, 4]. How can you adapt your approach to get the right side view?
hard
A. Rebuild the tree from preorder with nulls, then perform BFS right side view
B. Directly pick every second element from the preorder array
C. Use preorder array as is and treat it as right side view
D. Reverse the preorder array and pick first elements
Solution
Step 1: Understand preorder with nulls
The array represents tree nodes with nulls marking missing children, so tree structure is implicit.
Step 2: Rebuild tree then apply right side view
Reconstruct the binary tree from this array, then run BFS to get right side view nodes.
Final Answer:
Rebuild tree from preorder with nulls, then BFS -> Option A
Quick Check:
Need tree structure to find right side view [OK]
Hint: Rebuild tree from traversal before right side view [OK]
Common Mistakes:
Assuming preorder array directly gives right side view
Ignoring nulls and tree structure
Trying to pick nodes without tree reconstruction
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.