Skip to content
DeepForgeby svx
All problems
MediumData Structuresds-030

Level-Order Traversal

Problem

Return the level-order (breadth-first) traversal of a binary search tree built from the given values.

Insert the values in order (duplicates ignored), then process the tree level by level, collecting each level as its own list.

Return a list of levels, or [] for an empty tree.

Hint

Process the current level, collect its values, and build the next level from its children.

Test cases

case 1
in: [[5,3,8,1]]
expected: [[5],[3,8],[1]]
case 2
in: [[]]
expected: []
case 3
in: [[2]]
expected: [[2]]
case 4
in: [[10,5,15,3,7,12,20]]
expected: [[10],[5,15],[3,7,12,20]]
Starter codePython
def level_order(values):
    # Your code here
    pass

4 test cases · run your code against them in the editor