Printing BFS (Binary Tree) in Level Order with Specific Formatting

前端 未结 15 1389
情歌与酒
情歌与酒 2020-12-04 13:00

To begin with, this question is not a dup of this one, but builds on it.

Taking the tree in that question as an example,

    1 
   / \\
  2   3
 /            


        
15条回答
  •  暖寄归人
    2020-12-04 13:27

    This is breadth first search, so you can use a queue and recursively do this in a simple and compact way ...

    # built-in data structure we can use as a queue
    from collections import deque
    
    def print_level_order(head, queue = deque()):
        if head is None:
            return
        print head.data
        [queue.append(node) for node in [head.left, head.right] if node]
        if queue:
            print_level_order(queue.popleft(), queue)
    

提交回复
热议问题