Bird
Raised Fist0

Given the tree below, what is the value of depth after the second iteration of the while loop?

easy🧾 Code Trace Q12 of Q15
Tree: Depth-First Search - Maximum Depth of Binary Tree
Consider the following BFS-based Python code to compute the maximum depth of a binary tree. Given the tree below, what is the value of depth after the second iteration of the while loop? Tree structure: - Root node 1 - Left child 2 - Right child 3 - Left child of 2 is 4
from collections import deque

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def maxDepth(root):
    if root is None:
        return 0
    queue = deque([root])
    depth = 0
    while queue:
        level_size = len(queue)
        for _ in range(level_size):
            node = queue.popleft()
            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)
        depth += 1
    return depth

root = TreeNode(1, TreeNode(2, TreeNode(4)), TreeNode(3))
print(maxDepth(root))
A1
B2
C3
D4
Step-by-Step Solution
Solution:
  1. Step 1: Trace first iteration of while loop

    Initially, queue contains root (1). level_size=1. After processing node 1, enqueue its children 2 and 3. Increment depth to 1.
  2. Step 2: Trace second iteration of while loop

    Queue now has nodes 2 and 3. level_size=2. Process node 2 (enqueue 4), process node 3 (no children). Increment depth to 2.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Depth increments after each level processed; after second level depth=2 [OK]
Quick Trick: Depth increments after processing each tree level [OK]
Common Mistakes:
MISTAKES
  • Counting nodes instead of levels
  • Off-by-one in depth increment
  • Ignoring children enqueueing
Trap Explanation:
PITFALL
  • Confusing number of nodes processed with depth leads to off-by-one errors.
Interviewer Note:
CONTEXT
  • Tests candidate's ability to mentally execute BFS level order traversal code.
Master "Maximum Depth of Binary Tree" in Tree: Depth-First Search

3 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Tree: Depth-First Search Quizzes