Binary Tree Level Order Traversal in Java: Explanation & Practice
Traverse tree level by level (BFS)
Problem summary
Given a binary tree, return the level order traversal of its nodes' values (i.e., from left to right, level by level).
Starter code
public class Main {
public static void main(String[] args) {
// Tree: 3
// / \
// 9 20
// / \
// 15 7
// Print each level on new line: 3
9 20
15 7
}
}Expected output and test cases
- [3,9,20,null,null,15,7]
3 9 20 15 7
- [1]
1
- []
Hints
- Use Queue (LinkedList) for BFS
- Process nodes level by level
- For each level, process all nodes currently in queue
- Add children of each node to queue for next level
Related Data Structures & Algorithms exercises
- Practice Binary Tree Inorder Traversal in Java
- Practice Maximum Depth of Binary Tree in Java
- Practice Validate Binary Search Tree in Java
Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler