【问题标题】:Printing Binary Tree in Level Order without Left or Right in Python在Python中以没有左或右的级别顺序打印二叉树
【发布时间】:2018-01-28 13:25:56
【问题描述】:

此问题正在寻找this post 中给出的答案的替代方案。

如何使用以下二叉树结构创建一个字符串,该字符串在新行上具有树的每个级别:

# A Node is an object
# - value : Number
# - children : List of Nodes
class Node:
    def __init__(self, value, children):
        self.value = value
        self.children = children

我的问题是我习惯了这样的树结构:

class Node(object):
  def __init__(self, value, left=None, right=None):
    self.value = value
    self.left = left
    self.right = right

这是一个示例树:

exampleTree = Node(1,[Node(2,[]),Node(3,[Node(4,[Node(5,[]),Node(6,[Node(7,[])])])])])

这将打印为:

1 
23
4
56
7

非常感谢任何有关如何使用该新结构创建定义的帮助或想法。

【问题讨论】:

    标签: python python-3.x binary-tree


    【解决方案1】:

    您可以只使用list.extend添加子节点,而不是append逐个添加。

    class Node:
      def __init__(self, value, children):
        self.value = value
        self.children = children
    
    
    def traverse(root):
      curr = [root]
      while curr:
        next_level = []
        for n in curr:
          print(n.value, end='')
          next_level.extend(n.children)
        print()
        curr = next_level
    
    exampleTree = Node(1,[Node(2,[]),Node(3,[Node(4,[Node(5,[]),Node(6,[Node(7,[])])])])])
    
    traverse(exampleTree)
    

    打印

    1
    23
    4
    56
    7
    

    (对于没有阅读问题的任何人,这完全是this answer的派生词)

    【讨论】:

      【解决方案2】:

      您可以使用队列在树上执行 BFS:

      try:
          from queue import Queue # Python 3
      except ImportError:
          from Queue import Queue # Python 2
      q = Queue() # create new queue
      q.put(root) # where "root" is the root node of the tree
      while not q.empty():
          curr = q.get() # get next node from queue
          print(curr.value) # get node's value
          for child in curr.children:
              q.put(child) # add each child to the queue
      

      请注意,此解决方案适用于所有树,而不仅仅是二进制

      编辑:抱歉,没有意识到您希望同一级别中的所有内容都在同一行输出中。使用其他解决方案(或适当修改我的)

      【讨论】:

      • 如果你只想要一个普通的数据结构,我建议不要使用queue.Queue。该类旨在用于线程之间的同步通信(它具有您不需要的锁等)。相反,使用collections.deque(发音为deck,官方意思是双端队列),它只有你需要的东西。 queue.Queue 类在内部使用 deque
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-22
      • 1970-01-01
      • 1970-01-01
      • 2010-12-26
      • 1970-01-01
      • 1970-01-01
      • 2011-01-15
      相关资源
      最近更新 更多