Binary Tree Level Order Traversal
MediumTrees
Given the root of a binary tree, return the values of its nodes grouped by depth.
The result is a list of lists: the first inner list holds the root's value, the second holds every value one level below the root, and so on. Within each level, values appear from left to right. Return an empty list for an empty tree.
Trees are written in level order: values are listed level by level, left to right, and null marks a missing child (trailing nulls are omitted).
Example 1
- Input:
- root = [1,2,3,null,4,null,5]
- Output:
- [[1], [2, 3], [4, 5]]
- Explanation
- The bottom level takes 4 from under node 2 and 5 from under node 3. They come from different parents but share a depth, so they belong to the same level.
Example 2
- Input:
- root = [8,3,10,1,6,null,14,null,null,4,7,13]
- Output:
- [[8], [3, 10], [1, 6, 14], [4, 7, 13]]
- Explanation
- Level by level: 8; then 3 and 10; then 1, 6, 14; then 4 and 7 (children of 6) followed by 13 (child of 14), read left to right.
Example 3
- Input:
- root = [1,2,null,3]
- Output:
- [[1], [2], [3]]
- Explanation
- Each node has one child, so every level holds exactly one value.
Constraints
- The number of nodes is in the range
[0, 2000] -1000 <= Node.val <= 1000