Bird
Raised Fist0

Given the following iterative postorder traversal code, what is the final output when run on the tree: root = TreeNode(1, None, TreeNode(2, TreeNode(3)))?

easy🧾 Code Trace Q12 of Q15
Tree: Depth-First Search - Binary Tree Postorder Traversal
Given the following iterative postorder traversal code, what is the final output when run on the tree: root = TreeNode(1, None, TreeNode(2, TreeNode(3)))?
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
A[2, 3, 1]
B[1, 3, 2]
C[3, 2, 1]
D[3, 1, 2]
Step-by-Step Solution
  1. Step 1: Trace traversal on given tree

    Start at root(1), go left (None), push 1. Then peek 1, right child is 2, move to 2, push 2, go left to 3, push 3, left None.
  2. Step 2: Process nodes in postorder

    3 has no children, append 3. Back to 2, right visited, append 2. Back to 1, right visited, append 1.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Output matches postorder [3, 2, 1] [OK]
Quick Trick: Postorder output for this tree is [3,2,1] [OK]
Common Mistakes:
MISTAKES
  • Confusing order of appending nodes
  • Off-by-one in stack popping
Trap Explanation:
PITFALL
  • Candidates often confuse when to append node values, leading to preorder-like output.
Interviewer Note:
CONTEXT
  • Tests ability to mentally execute iterative postorder code and track variables.
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