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

  1. Use Queue (LinkedList) for BFS
  2. Process nodes level by level
  3. For each level, process all nodes currently in queue
  4. Add children of each node to queue for next level

Related Data Structures & Algorithms exercises

Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler