Bird
Raised Fist0

Given the following iterative postorder traversal code using one stack and a pointer, what is the output for the tree: root = TreeNode(1, TreeNode(2), TreeNode(3))?

easy🧾 Code Trace Q3 of Q15
Tree: Depth-First Search - Binary Tree Postorder Traversal
Given the following iterative postorder traversal code using one stack and a pointer, what is the output for the tree: root = TreeNode(1, TreeNode(2), TreeNode(3))? ```python from typing import Optional, List class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def postorderTraversal(root: Optional[TreeNode]) -> List[int]: 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[3, 2, 1]
B[2, 3, 1]
C[1, 2, 3]
D[1, 3, 2]
Step-by-Step Solution
Solution:
  1. Step 1: Trace traversal on tree

    Start at root(1), go left to 2 (no children), append 2, back to 1, go right to 3 (no children), append 3, then append 1.
  2. Step 2: Confirm output order

    Postorder is left, right, node -> [2, 3, 1].
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Output matches postorder traversal [OK]
Quick Trick: Postorder outputs left-right-node order [OK]
Common Mistakes:
MISTAKES
  • Confusing preorder output
  • Appending node before children
Trap Explanation:
PITFALL
  • Candidates often confuse output with preorder or inorder traversal orders.
Interviewer Note:
CONTEXT
  • Tests candidate's ability to mentally execute iterative postorder 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