v9.1.1
Menu

Binary Tree Level Order Traversal

mediumFREETreesBlind 75

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

Input
3,9,20,null,null,15,7
Output
3
9 20
15 7
Reasoning
  • The input 3,9,20,null,null,15,7 lists the tree top to bottom, left to right, with null marking a missing child. The root is 3; its children are 9 (left) and 20 (right); the two nulls say 9 has no children, so 15 and 7 are the left and right children of 20.
  • A node's level is its depth dd (edges from the root): d(3)=0d(3)=0, d(9)=d(20)=1d(9)=d(20)=1, d(15)=d(7)=2d(15)=d(7)=2.
  • The traversal groups values by depth, one group for each d=0,1,…,hd = 0, 1, \dots, h, where hh is the tree's height. Here h=2h = 2, so there are h+1=3h + 1 = 3 groups. Within a group, values keep their left-to-right order in the tree.
  • That gives the groups [3][3], [9,20][9, 20], [15,7][15, 7]: a list of 3 lists. Printed one level per line, space-separated, they read 3, 9 20, 15 7.
  • Notice that 15 7 follows directly on the third line even though 9 has 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
  • -1000 <= Node.val <= 1000

Learn this in

More from Blind 75

solution.py

Test results

Sign in to run your code against the test cases.