You are given the root
of a binary tree. Your task is to return the level order traversal of its nodes' values. This means you should traverse the tree level by level, from left to right, and return a list of lists, where each inner list represents a level.
For example:
Example 1:
root = [3,9,20,null,null,15,7]
[[3],[9,20],[15,7]]
The tree looks like this:
3
/ \
9 20
/ \
15 7
Example 2:
root = [1]
[[1]]
The tree looks like this:
1
Example 3:
root = []
[]
This is an empty tree.
Constraints:
[0, 2000]
. 0 <= number of nodes <= 2000.Can you implement an algorithm to solve this problem efficiently?
The most straightforward way to perform a level order traversal is to use Breadth-First Search (BFS). We can use a queue to keep track of the nodes to visit. At each level, we visit all the nodes at that level before moving on to the next level.
number of nodes at current level
times:
The optimal approach is essentially the same as the naive approach since BFS is inherently suited to level order traversal. There is no significant way to improve the algorithmic complexity.
null
, return an empty list.import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) {
return result;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int levelSize = queue.size();
List<Integer> currentLevel = new ArrayList<>();
for (int i = 0; i < levelSize; i++) {
TreeNode node = queue.poll();
currentLevel.add(node.val);
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
result.add(currentLevel);
}
return result;
}
}