Binary Tree Inorder Traversal (Recursive) (Recursion & Backtracking)
Binary Tree Inorder Traversal (Recursive) is a easy recursion & backtracking problem solved with the basic 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 up.
Problem
Return the inorder traversal of a binary tree: left subtree, node, right subtree. You already did this in class; here it is the warm-up for thinking recursively about trees.
Examples
Example 1
- Input
root = [1, null, 2, 3]- Output
[1, 3, 2]
Example 2
- Input
root = [2, 1, 3]- Output
[1, 2, 3]- Why
- Inorder on a BST gives sorted order.
Constraints
- The tree has
0to100nodes.
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 | O(n) | O(h) |
| Iterative (explicit stack) | O(n) | O(h) |
1Recursive
O(n)O(h)h is the tree height: O(log n) if balanced, O(n) if skewed.Left subtree, then the node, then the right subtree. The recursion is the problem's definition, which is why this is the classic first tree-recursion exercise.
- If node is null, return.
- go(left); add node.val; go(right).
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> out = new ArrayList<>();
go(root, out);
return out;
}
private void go(TreeNode node, List<Integer> out) {
if (node == null) return;
go(node.left, out);
out.add(node.val);
go(node.right, out);
}
}class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
out = []
self.go(root, out)
return out
def go(self, node: Optional[TreeNode], out: List[int]) -> None:
if node is None:
return
self.go(node.left, out)
out.append(node.val)
self.go(node.right, out)class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> out;
go(root, out);
return out;
}
private:
void go(TreeNode* node, vector<int>& out) {
if (node == nullptr) return;
go(node->left, out);
out.push_back(node->val);
go(node->right, out);
}
};function inorderTraversal(root) {
const out = [];
go(root, out);
return out;
}
function go(node, out) {
if (node === null) return;
go(node.left, out);
out.push(node.val);
go(node.right, out);
}2Iterative (explicit stack)
O(n)O(h)Simulate the call stack: push nodes while going left, then pop one, visit it and switch to its right child.
- While cur != null or the stack is not empty: push all lefts; pop; visit; 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 = []
st = []
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
- Empty tree
- Skewed tree (depth n)
Hints
Hint 1
Trust the recursion: assume inorder(left) already works, then add the root, then inorder(right).
FAQ
What is the best time complexity for Binary Tree Inorder Traversal (Recursive)?
Iterative (explicit stack) runs in O(n) time and O(h) extra space.
Which pattern does Binary Tree Inorder Traversal (Recursive) use?
It is a recursion & backtracking problem that uses the basic recursion pattern. Other problems with the same pattern: Factorial of a number, Fibonacci Number, Basic Backtracking Template.
Is there a brute force solution for Binary Tree Inorder Traversal (Recursive)?
Yes. Recursive takes O(n) time and O(h) space. Left subtree, then the node, then the right subtree.
Which edge cases should I test for Binary Tree Inorder Traversal (Recursive)?
Empty tree; Skewed tree (depth n).