Skip to problem
←

Binary Tree Inorder Traversal

Easy 0 attempts

Given the root of a binary tree, return its node values in inorder: traverse the left subtree, visit the current node, then traverse the right subtree. Use an explicit stack for an iterative traversal.

The tree is not necessarily a binary search tree, so the returned values need not be sorted. An empty tree returns an empty array.

Function contract

Test inputs are level-order arrays with null for missing children. The function receives tree nodes with val, left, and right properties.

Output: Return an array of node values in left-subtree, node, right-subtree order. An empty tree returns [].

Example 1

Input
root = [1,null,2,3]
Output
[1,3,2]

Example 2

Input
root = []
Output
[]

Example 3

Input
root = [1]
Output
[1]
Constraints
  • 0 <= Number of nodes <= 100
  • -100 <= Node.val <= 100

Approach: Iterative with Stack

Use a stack to simulate the recursive inorder traversal. Push all left children onto the stack, then pop, record the value, and move to the right child. Repeat until both stack and current pointer are exhausted.

javascript
function binaryTreeInorderTraversal(root) {
  const result = [],
    stack = [];
  let curr = root;
  while (curr || stack.length) {
    while (curr) {
      stack.push(curr);
      curr = curr.left;
    }
    curr = stack.pop();
    result.push(curr.val);
    curr = curr.right;
  }
  return result;
}

Time Complexity: O(n)

Space Complexity: O(h) auxiliary stack space, where h is tree height (O(n) for a skewed tree), plus O(n) for the returned array.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript