49. Binary Tree Inorder Traversal
Return the in-order traversal of a binary tree: left subtree, then the node, then the right subtree. Try it iteratively too.
Example 1
Input:
root = [1,null,2,3]Output:
[1,3,2]Example 2
Input:
root = []Output:
[]Hint 1
Recursive version: inorder(left), visit, inorder(right).
Hint 2
Iterative: a stack replaces the call stack.
Approach 1: Recursive
Three lines of recursion.
⏱ Time O(n)💾 Space O(h)
Approach 2: Iterative with stack ✅
Push the left spine, pop, then move right.
⏱ Time O(n)💾 Space O(h)
Reference solution for Iterative with stack (time O(n), space O(h)). Each solution passes every test in all four languages.
class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
res, stack, node = [], [], root
while node or stack:
while node: # go as far left as possible
stack.append(node)
node = node.left
node = stack.pop() # visit
res.append(node.val)
node = node.right # then the right subtree
return resclass Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
Deque<TreeNode> stack = new ArrayDeque<>();
TreeNode node = root;
while (node != null || !stack.isEmpty()) {
while (node != null) { stack.push(node); node = node.left; }
node = stack.pop();
res.add(node.val);
node = node.right;
}
return res;
}
}class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
vector<TreeNode*> st;
TreeNode* node = root;
while (node || !st.empty()) {
while (node) { st.push_back(node); node = node->left; }
node = st.back(); st.pop_back();
res.push_back(node->val);
node = node->right;
}
return res;
}
};function inorderTraversal(root) {
const res = [], stack = [];
let node = root;
while (node || stack.length) {
while (node) { stack.push(node); node = node.left; }
node = stack.pop();
res.push(node.val);
node = node.right;
}
return res;
}Try solving it yourself first. Interviewers care more about how you explain the approach than about the finished code.
Watch the core idea of this problem step by step. Change the input and press Visualize.
Explained in the lesson Binary Trees & BSTs.
Run your code to see results here.