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

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

    class TNode:
      def __init__(self, data, left=None, right=None):
        self.data = data
        self.left = left
        self.right = right
    
    class BST:
      def __init__(self, root):
        self._root = root
    
      def bfs(self):
        list = [self._root]
        while len(list) > 0:
            print [e.data for e in list]
            list = [e.left for e in list if e.left] + \
                   [e.right for e in list if e.right]
    bst = BST(TNode(1, TNode(2, TNode(4), TNode(5)), TNode(3, TNode(6), TNode(7))))
    bst.bfs()
    

提交回复
热议问题