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

前端 未结 15 1388
情歌与酒
情歌与酒 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:30

    I think what you expecting is to print the nodes at each level either separated by a space or a comma and the levels be separated by a new line. This is how I would code up the algorithm. We know that when we do a breadth-first search on a graph or tree and insert the nodes in a queue, all nodes in the queue coming out will be either at the same level as the one previous or a new level which is parent level + 1 and nothing else.

    So when you are at a level keep printing out the node values and as soon as you find that the level of the node increases by 1, then you insert a new line before starting to print all the nodes at that level.

    This is my code which does not use much memory and only the queue is needed for everything.

    Assuming the tree starts from the root.

    queue = [(root, 0)]  # Store the node along with its level. 
    prev = 0
    while queue:
      node, level = queue.pop(0)
      if level == prev:
        print(node.val, end = "")
      else:
        print()
        print(node.val, end = "")
      if node.left:
        queue.append((node.left, level + 1))
      if node.right:
        queue.append((node.right, level + 1))
      prev = level
    

    At the end all you need is the queue for all the processing.

提交回复
热议问题