#94

Binary Tree Inorder 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 solution uses an iterative approach with a stack to simulate the recursive behavior of inorder traversal. This allows us to avoid the overhead of recursive calls while maintaining the same order of traversal.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize an empty stack and a current node pointer starting at the root.
  2. 2Step 2: While the current node is not null or the stack is not empty, do the following:
  3. 3Step 3: Push all left children of the current node onto the stack.
  4. 4Step 4: Pop the top node from the stack, add its value to the result list, and move to its right child.
  5. 5Step 5: Repeat until both the stack is empty and the current node is null.
solution.py10 lines
1def inorderTraversal(root):
2    result, stack, current = [], [], root
3    while current or stack:
4        while current:
5            stack.append(current)
6            current = current.left
7        current = stack.pop()
8        result.append(current.val)
9        current = current.right
10    return result

Complexity note: The time complexity is O(n) because we visit each node exactly once. The space complexity is O(n) due to the stack used to store nodes during traversal.

  • 1Inorder traversal visits nodes in a specific order: left, root, right.
  • 2Using a stack allows us to simulate the recursive call stack without actual recursion.

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