#144

Binary Tree Preorder Traversal

Easy Iterative preorder with a stack

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Return the values of a binary tree in preorder (node, left subtree, right subtree).

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: node first, then left, then right.

Why this works: with a stack, pop and visit; push right before left so left comes out first.

Example: tree 1 (left 2, right 3)

pop 1 → push 3, 2pop 2, pop 3 → [1, 2, 3]

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Pushing left before right, which produces node-right-left order.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(h).
Topic: Binary Trees
🎬 Episodes 53–60: video coming soon