Skip to main content

Binary Tree Level Order Traversal


Binary Tree Level Order Traversal: Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).

Example 1:

image

Input: root = [3,9,20,null,null,15,7]
Output: [[3],[9,20],[15,7]]

Example 2:
Input: root = [1]
Output: [[1]]

Example 3:
Input: root = []
Output: []

Constraints:
  • The number of nodes in the tree is in the range [0, 2000].
  • -1000 <= Node.val <= 1000

Try this Problem on your own or check similar problems:

  1. Binary Tree Level Order Traversal II
  2. Average of Levels in Binary Tree
  3. Binary Tree Zigzag Level Order Traversal
Solution:
public List<List<Integer>> levelOrder(TreeNode root) {
if(root == null) return List.of();

List<List<Integer>> result = new ArrayList<>();
Queue<TreeNode> q = new LinkedList<>();

q.add(root);
while(!q.isEmpty()){
int size = q.size();
List<Integer> level = new ArrayList<>();
while(size-->0){
TreeNode node = q.poll();
if(node.left != null){
q.add(node.left);
}
if(node.right != null){
q.add(node.right);
}
level.add(node.val);
}
result.add(level);
}

return result;
}

Time/Space Complexity:
  • Time Complexity: O(n)
  • Space Complexity: O(n)

Explanation:

The implementation is identical to the Binary Tree Level Order Traversal II and Average of Levels in Binary Tree. We maintain a queue of elements which represent our current level, we loop over current element candidates and try to add left and right nodes if they exist. Finally, we return the list of levels as our result.