Binary Tree Inorder Traversal in Java: Explanation & Practice
Traverse tree in Left-Root-Right order
Problem summary
Given a binary tree, return the inorder traversal of its nodes' values. Implement iteratively using a stack.
Starter code
public class Main {
public static void main(String[] args) {
// Tree: 1
// \
// 2
// /
// 3
// Inorder: Left, Root, Right
// Print: 1 3 2
}
}Expected output and test cases
- [1,null,2,3]
1 3 2
- [] → empty
- [1]
1
Hints
- Recursive: inorder(left), visit root, inorder(right)
- Iterative: use stack, go left as far as possible
- Pop node, add to result, then go right
- Repeat until stack empty and current is null
Related Data Structures & Algorithms exercises
- Practice Largest Rectangle in Histogram in Java
- Practice Min Stack in Java
- Practice Maximum Depth of Binary Tree in Java
Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler