Binary Tree Level Order Traversal
Given a binary tree (level-order array), return the level order traversal: the node values grouped by level, from the root level down, with each level's values in left-to-right order.
level_order(root) returns a list of lists, one inner list per level (an empty list for an empty tree). The tests print each level on a separate line, space-separated.
Example
3,9,20,null,null,15,7
3 9 20 15 7
- The input
3,9,20,null,null,15,7lists the tree top to bottom, left to right, withnullmarking a missing child. The root is3; its children are9(left) and20(right); the twonulls say9has no children, so15and7are the left and right children of20. - A node's level is its depth (edges from the root): , , .
- The traversal groups values by depth, one group for each , where is the tree's height. Here , so there are groups. Within a group, values keep their left-to-right order in the tree.
- That gives the groups , , : a list of 3 lists. Printed one level per line, space-separated, they read
3,9 20,15 7. - Notice that
15 7follows directly on the third line even though9has no children: missing nodes contribute nothing, leaving no gap. An empty tree has no levels, so its result is an empty list.
Constraints
- 0 <= number of nodes <= 2000