#144

Binary Tree Preorder Traversal

Easy
StackTreeDepth-First SearchBinary TreeStackDepth-First Search
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses an iterative method with a stack to simulate the recursive behavior of preorder traversal. This avoids the overhead of recursive calls and allows us to control the order of node processing more efficiently.

⚙️

Algorithm

6 steps
  1. 1Step 1: Initialize an empty stack and push the root node onto it.
  2. 2Step 2: While the stack is not empty, pop the top node.
  3. 3Step 3: Add the popped node's value to the result list.
  4. 4Step 4: Push the right child of the popped node onto the stack (if it exists).
  5. 5Step 5: Push the left child of the popped node onto the stack (if it exists).
  6. 6Step 6: Repeat until the stack is empty.
solution.py12 lines
1def preorderTraversal(root):
2    if not root:
3        return []
4    stack, result = [root], []
5    while stack:
6        node = stack.pop()
7        result.append(node.val)
8        if node.right:
9            stack.append(node.right)
10        if node.left:
11            stack.append(node.left)
12    return result

Complexity note: The time complexity is O(n) because we visit each node exactly once. The space complexity is O(n) in the worst case due to the stack storing nodes, especially if the tree is skewed.

  • 1Preorder traversal visits the root before its children.
  • 2Using a stack allows us to simulate recursion iteratively.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.