Binary Tree Inorder Traversal (Iterative)
Binary Tree Inorder Traversal (Iterative) is a easy trees & bst problem solved with the recursion pattern.
The best approach, iterative (explicit stack), runs in O(n) time and O(h) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from recursive (reference) up.
Problem
Return the inorder traversal of a binary tree iteratively, using your own stack in place of recursion.
Examples
Example 1
- Input
root = [5, 3, 8, 1, 4]- Output
[1, 3, 4, 5, 8]
Example 2
- Input
root = []- Output
[]
Constraints
- The tree has
0to100nodes. - Solve it without recursion.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (2 examples, or your own). Submit also runs 13 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Recursive (reference) | O(n) | O(h) |
| Iterative (explicit stack) | O(n) | O(h) |
1Recursive (reference)
O(n)O(h)Left, node, right with the call stack.
- inorder(left); add; inorder(right).
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> out = new ArrayList<>();
go(root, out);
return out;
}
private void go(TreeNode n, List<Integer> out) {
if (n == null) return;
go(n.left, out);
out.add(n.val);
go(n.right, out);
}
}class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
out: List[int] = []
self.go(root, out)
return out
def go(self, n: Optional[TreeNode], out: List[int]) -> None:
if n is None:
return
self.go(n.left, out)
out.append(n.val)
self.go(n.right, out)class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> out;
go(root, out);
return out;
}
private:
void go(TreeNode* n, vector<int>& out) {
if (n == nullptr) return;
go(n->left, out);
out.push_back(n->val);
go(n->right, out);
}
};function inorderTraversal(root) {
const out = [];
go(root, out);
return out;
}
function go(n, out) {
if (n === null) return;
go(n.left, out);
out.push(n.val);
go(n.right, out);
}2Iterative (explicit stack)
O(n)O(h)The stack holds the nodes whose left subtree is being explored. Push down the left spine; pop gives the next node in sorted order; then continue with its right subtree.
- cur = root.
- While cur != null or the stack is not empty: while cur != null: push, cur = cur.left.
- cur = pop(); visit; cur = cur.right.
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> out = new ArrayList<>();
Deque<TreeNode> st = new ArrayDeque<>();
TreeNode cur = root;
while (cur != null || !st.isEmpty()) {
while (cur != null) { st.push(cur); cur = cur.left; }
cur = st.pop();
out.add(cur.val);
cur = cur.right;
}
return out;
}
}class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
out: List[int] = []
st: List[TreeNode] = []
cur = root
while cur is not None or st:
while cur is not None:
st.append(cur)
cur = cur.left
cur = st.pop()
out.append(cur.val)
cur = cur.right
return outclass Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> out;
stack<TreeNode*> st;
TreeNode* cur = root;
while (cur != nullptr || !st.empty()) {
while (cur != nullptr) { st.push(cur); cur = cur->left; }
cur = st.top(); st.pop();
out.push_back(cur->val);
cur = cur->right;
}
return out;
}
};function inorderTraversal(root) {
const out = [];
const st = [];
let cur = root;
while (cur !== null || st.length > 0) {
while (cur !== null) { st.push(cur); cur = cur.left; }
cur = st.pop();
out.push(cur.val);
cur = cur.right;
}
return out;
}Edge cases to test
- Only right children
- Only left children
Hints
Hint 1
Keep going left, pushing nodes. When you cannot go further, pop, visit, then turn right.
FAQ
What is the best time complexity for Binary Tree Inorder Traversal (Iterative)?
Iterative (explicit stack) runs in O(n) time and O(h) extra space.
Which pattern does Binary Tree Inorder Traversal (Iterative) use?
It is a trees & bst problem that uses the recursion pattern. Other problems with the same pattern: Binary Tree Inorder Traversal (Recursive), Binary Tree Preorder Traversal (Recursive), Binary Tree Postorder Traversal (Recursive).
Is there a brute force solution for Binary Tree Inorder Traversal (Iterative)?
Yes. Recursive (reference) takes O(n) time and O(h) space. Left, node, right with the call stack.
Which edge cases should I test for Binary Tree Inorder Traversal (Iterative)?
Only right children; Only left children.