Bird
Raised Fist0

Consider this buggy iterative postorder traversal code:

medium🐞 Bug Identification Q14 of Q15
Tree: Depth-First Search - Binary Tree Postorder Traversal
Consider this buggy iterative postorder traversal code:
def postorderTraversal(root):
    result = []
    stack = []
    last_visited = None
    current = root
    while current or stack:
        while current:
            stack.append(current)
            current = current.left
        peek_node = stack[-1]
        if peek_node.right and last_visited == peek_node.right:
            current = peek_node.right
        else:
            result.append(peek_node.val)
            last_visited = stack.pop()
    return result
What is the bug in this code?
AThe inner while loop should traverse right children instead of left
BThe condition should check if last_visited != peek_node.right, not == peek_node.right
CThe last_visited variable is never updated
DThe result list is appended before traversing the left subtree
Step-by-Step Solution
  1. Step 1: Examine condition for traversing right subtree

    Correct logic requires moving to right child if it exists and was not visited yet, so condition must be last_visited != peek_node.right.
  2. Step 2: Identify effect of wrong condition

    Using last_visited == peek_node.right causes skipping right subtree traversal or infinite loops.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Fixing condition restores correct postorder traversal [OK]
Quick Trick: Check last_visited != right child to avoid revisiting [OK]
Common Mistakes:
MISTAKES
  • Using == instead of !=
  • Not updating last_visited
  • Appending too early
Trap Explanation:
PITFALL
  • The subtle equality vs inequality in condition is easy to overlook but critical.
Interviewer Note:
CONTEXT
  • Tests ability to spot subtle logical bugs in iterative traversal code.
Master "Binary Tree Postorder Traversal" 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