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

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

    This is mostly the same code as provided by Alex Martelli except this is modified for python 3.

    class Node(object):
      def __init__(self, value, left=None, right=None):
        self.value = value
        self.left = left
        self.right = right
    
    def traverse(rootnode):
      thislevel = [rootnode]
      while thislevel:
        nextlevel = list()
        for n in thislevel:
          print (n.value,' ', end=''),
          if n.left: nextlevel.append(n.left)
          if n.right: nextlevel.append(n.right)
        print(" ")
        thislevel = nextlevel
    
    t = Node(1, Node(2, Node(4, Node(7))), Node(3, Node(5), Node(6)))
    
    traverse(t)
    

提交回复
热议问题