Level Order Traversal
Problem
The tree is given in level order on one line, with null for a missing child. Print the values level by level, one line per level, from left to right.
Constraints
- 1 <= n <= 10^4 nodes
Examples
Input
3 9 20 null null 15 7
Output
3 9 20 15 7
Solutions
Breadth-first search with a queue visits the tree level by level. Counting the nodes in the queue at the start of a round tells us where the current level ends.
/*
* Problem : Process a binary tree.
* Input : One line: the tree in level order, null for a missing child.
* Output : One line for each level.
* Approach: Breadth-first search by levels.
* Time : O(n)
* Space : O(w)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// Step 1: A tree node has a value and links to the left and right child. null means: no child.
static class TreeNode {
int value;
TreeNode left;
TreeNode right;
TreeNode(int value) {
this.value = value;
}
}
// This method builds a tree from the level order tokens. A queue keeps the nodes that still need children.
static TreeNode build(String[] tokens) {
if (tokens.length == 0 || tokens[0].equals("null")) {
return null;
}
TreeNode root = new TreeNode(Integer.parseInt(tokens[0]));
java.util.ArrayDeque<TreeNode> queue = new java.util.ArrayDeque<>();
queue.add(root);
int i = 1;
while (!queue.isEmpty() && i < tokens.length) {
TreeNode node = queue.poll();
if (i < tokens.length && !tokens[i].equals("null")) {
node.left = new TreeNode(Integer.parseInt(tokens[i]));
queue.add(node.left);
}
i++;
if (i < tokens.length && !tokens[i].equals("null")) {
node.right = new TreeNode(Integer.parseInt(tokens[i]));
queue.add(node.right);
}
i++;
}
return root;
}
// This method solves the task. It receives the input and returns the answer.
static String[] solve(String s) {
TreeNode root = build(s.trim().split(" "));
java.util.List<String> output = new java.util.ArrayList<>();
java.util.ArrayDeque<TreeNode> queue = new java.util.ArrayDeque<>();
queue.add(root);
// Step 2: Process one level at a time. At the start of a round the queue holds exactly one level.
while (!queue.isEmpty()) {
int size = queue.size();
StringBuilder line = new StringBuilder();
// Step 3: Take all nodes of this level. Their children form the next level.
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
if (i > 0) {
line.append(" ");
}
line.append(node.value);
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}
output.add(line.toString());
}
return output.toArray(new String[0]);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.hasNextLine() ? scanner.nextLine() : "";
System.out.println(String.join("\n", solve(s)));
}
}
Hints (1)
- Which data structure gives first-in, first-out order?