AlgoInsight

DSA problem

Binary Tree Inorder Traversal

EasyTree Traversal - In OrderPattern: Tree Traversal - In Ordertop75FreeAmazonMicrosoftGoogleBloombergAppleMeta

Given the root of a binary tree, return the inorder traversal of its nodes' values. Inorder means visiting the left subtree first, then the current node, and finally the right subtree — a left-node-right ordering that is the foundation of nearly every BST algorithm.

The recursive definition is elegant and almost matches the English description verbatim: traverse the left subtree, record the current value, then traverse the right subtree. It costs O(n) time and O(h) call-stack space, where h is the height of the tree. For a balanced tree h is O(log n), but for a skewed tree h degenerates to O(n), which can overflow the call stack on deep inputs.

The iterative version makes that stack explicit using an array-backed stack. Starting from the root, we walk left as far as possible, pushing each node onto the stack. When we cannot go left anymore, we pop a node, record its value, and switch to its right child — repeating the same left-walk from there. This simulates exactly what recursion would do and is the canonical interview answer because it avoids hidden recursion depth limits.

A more advanced O(1)-space option is Morris traversal, which temporarily rewires right pointers of the rightmost predecessors to create a thread back to the root, then restores them. It is interesting but rarely required — the iterative-with-stack approach is what most interviewers expect and what we showcase here as canonical.

Examples

Example 1
Input: root = [1,null,2,3]
Output: [1,3,2]
Explanation: The root 1 has no left child, so we record 1, then visit the right subtree rooted at 2. Node 2 has left child 3 (visited first) and no right child, so the final inorder list is [1,3,2].
Example 2
Input: root = []
Output: []
Explanation: An empty tree produces an empty inorder list.
Example 3
Input: root = [1,2,3,4,5,6,7]
Output: [4,2,5,1,6,3,7]
Explanation: For the perfect binary tree the left subtree contributes [4,2,5], then root 1, then the right subtree contributes [6,3,7].

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

binary-treetree-traversalinorderstackiterative

Browse all DSA problems