Binary Tree Level Order Traversal
Add a queue-based level order (breadth-first) traversal to BinTree, visiting the sample tree one level at a time.
This exercise builds on Binary Tree Basics and Binary Tree Traversals (preorder/inorder/postorder) and adds a fourth way to visit every node: level order traversal, also called breadth-first traversal. Unlike the other three -- which go deep before wide (depth-first) -- level order visits the tree one level at a time, left to right.
The idea
Preorder/inorder/postorder are naturally recursive because they're depth-first. Level order is breadth-first, so instead of relying on the call stack, it uses an explicit queue:
- Add the root to a queue, followed by a
nullmarker -- the marker means "end of the current level." - Loop while the queue isn't empty: remove the front item.
- If it's a real node, print it, then enqueue its left and right children (if they exist).
- If it's the
nullmarker, a full level has just finished: print a newline. If the queue is now empty, stop -- there's nothing left. Otherwise, enqueue anothernullto mark the end of the level that's about to start.
public void levelOrder(){
if(root == null){
return;
}
Queue<Node<T>> queue = new LinkedList<>();
queue.add(root);
queue.add(null);
while(!queue.isEmpty()){
Node<T> node = queue.remove();
if(node != null){
System.out.printf(node.data + " , ");
if(node.left!= null){
queue.add(node.left);
}
if(node.right!= null){
queue.add(node.right);
}
}
else{
// We have reached to a new level
System.out.println();
if(queue.isEmpty()){
break;
}
queue.add(null);
}
}
}
The sample tree
1
|- left: 2
| |- left: 4
| | `- left: 8
| `- right: 5
| `- left: 9
`- right: 3
|- left: 6
`- right: 7
|- left: 10
`- right: 11
`- right: 12
See the Solutions tab for the full Java implementation.
This is a foundational exercise -- there are no graded test cases for it, since levelOrder() prints rather than returns a value. The level-by-level output below (verified by hand against the tree above) serves as a worked example instead.
Example 1
Input: levelOrder() on the sample tree -- level 0
Output: 1
Explanation: Just the root.
Example 2
Input: level 1
Output: 2 , 3
Explanation: Root's two children, left to right.
Example 3
Input: level 2
Output: 4 , 5 , 6 , 7
Explanation: Every node two levels below the root, left to right.
Example 4
Input: level 3
Output: 8 , 9 , 10 , 11
Example 5
Input: level 4
Output: 12
Explanation: The deepest node in the tree.
Constraints
- Uses the same 12-node sample tree as Binary Tree Basics.
- Each node is visited exactly once, level by level, left to right within a level.
Follow-up
Later exercises in the Binary Trees series (height/depth, balancing, search) will also operate on this same tree.
Hints
Companies
No companies reported yet.
Discussion
Sign in to join the discussion.
Loading discussion...
Test results
This question doesn't have a code exercise.