Instructions
You are given the root of a binary tree. Return the values of its nodes level by level.
The root is level 0, its children are level 1, their children are level 2, and so on. Return a list with one inner list per level, from the top level down. Inside each inner list, put the values from left to right.
If the tree is empty, return an empty list [].
How the input is shown
A tree is shown as a list of values in level order: row by row from the top, and left to right in each row. null means "no child here", and nulls at the end are left out. For example, [4, 2, 7, null, 3] is a root 4 with left child 2 and right child 7, and 2 has only a right child, 3.
Your function receives the root as a TreeNode (fields val, left, right), or null for an empty tree. It returns a plain list of lists of numbers.
Hint: use a queue. At the start of each level, the number of nodes in the queue is the number of nodes in that level.
Examples
Example 1
- Input:
- [8,3,10,1,6,null,14]
- Output:
- [[8],[3,10],[1,6,14]]
Level 0 is the root 8. Level 1 is 3 and 10. Level 2 is 1 and 6 (children of 3) and then 14 (right child of 10).
Example 2
- Input:
- []
- Output:
- []
The tree has no nodes, so there are no levels.
Example 3
- Input:
- [2,null,5,null,7,4]
- Output:
- [[2],[5],[7],[4]]
Each node has only one child: 2 has right child 5, 5 has right child 7, and 7 has left child 4. So every level holds one value.
Constraints
- The number of nodes is between
0and35. -100 <= Node.val <= 100- Values can repeat.
3 examples run when you press Run. Submit checks every hidden test too.
- Input:
- [8,3,10,1,6,null,14]
- Expected:
- [[8],[3,10],[1,6,14]]
- Input:
- []
- Expected:
- []
- Input:
- [2,null,5,null,7,4]
- Expected:
- [[2],[5],[7],[4]]
Run checks your code against the 3 examples. Submit checks it against all 123 tests and needs a free account. You can also try ideas in the free JavaScript or Python compiler.