【问题标题】:How can I print a binary tree level by level如何逐级打印二叉树
【发布时间】:2011-03-26 21:04:59
【问题描述】:

如何使用 python 从顶部开始逐级打印二叉树中的数据?

我对此很陌生,我不知道如何开始。

from collections import deque

class EmptyTree(object):
    def isEmpty(self):
        return True

    def __str__(self):
        return ""    

class BinaryTree(object):

    THE_EMPTY_TREE = EmptyTree()

    def __init__(self, item):
        self._root = item
        self._left = BinaryTree.THE_EMPTY_TREE
        self._right = BinaryTree.THE_EMPTY_TREE

    def isEmpty(self):
        return False

    def getRoot(self):
        return self._root

    def getLeft(self):
        return self._left

    def getRight(self):
        return self._right

    def setRoot(self, item):
        self._root = item

    def setLeft(self, tree):
        self._left = tree

    def setRight(self, tree):
        self._right = tree

    def removeLeft(self):
        left = self._left
        self._left = BinaryTree.THE_EMPTY_TREE
        return left

    def removeRight(self):
        right = self._right
        self._right = BinaryTree.THE_EMPTY_TREE
        return right

    def __str__(self):
        """Returns a string representation of the tree
        rotated 90 degrees to the left."""
        def strHelper(tree, level):
            result = ""
            if not tree.isEmpty():
                result += strHelper(tree.getRight(), level + 1)
                result += "| " * level
                result += str(tree.getRoot()) + "\n"
                result += strHelper(tree.getLeft(), level + 1)
            return result
        return strHelper(self, 0)

【问题讨论】:

  • 如果您还没有开始编写遍历,您应该阅读您的书(或其他参考,如Wikipedia),他们会尝试。
  • 我看过但找不到任何有用的东西。

标签: python tree binary-tree


【解决方案1】:

您可以将逐级打印二叉树视为从根开始对树进行广度优先搜索。在广度优先搜索中,您在距离为 2 的节点之前探索距离根节点 1 的所有节点,在距离为 3 的节点之前探索距离根节点 2 的节点,等等。

我其实不懂任何 Python 编程,但是这个算法的伪代码很简单。鉴于 Python 本质上是可执行的伪代码,我无法想象将其转换为合法的 Python 有那么困难。 :-)

Create a queue Q of nodes to visit.
Enqueue the tree root into Q.

While Q is not empty:
    Dequeue an element from the queue, call it u.
    Output u.

    If u has a left child, add that to the queue.
    If u has a right child, add that to the queue.

希望这会有所帮助!并为缺乏真正的代码道歉;学习 Python 仍然在我的 TODO 清单上。

【讨论】:

    【解决方案2】:

    尝试为此使用递归。如果您使用树为空的基本条件,您可以简单地说:

    def printTree(me):
      if isEmpty(me):
        return ""
      else:
        return getRoot(me) + printTree(getLeft(me)) + printTree(getRight(me))
    

    这里的想法是调用树的左右分支上的函数并将它们附加到包含您所在树的根的结果中。如果树有一个空分支,则该函数将附加一个空字符串并“继续滚动”。

    【讨论】:

      【解决方案3】:

      这是一些将逐级打印二叉树的代码。不过我使用了不同的类定义。

      from collections import deque
      
      def treeLevels(self):
              # Two queues, one for the nodes one for the level of the nodes.
              Q = deque()
              L = deque()
      
              # Initiation and printing the root.
              Q.append(self.root)
              level = 0
              L.append(level)
              print level, [self.root.key]
      
              while len(Q) > 0:
                  u = Q.popleft()
                  l = L.popleft()
      
                  # For the current node if it has a left or right child,
                  # add it to the queue and with its corresponding level + 1.
                  if u.left != None:
                      Q.append(u.left)
                      L.append(l + 1)
                  if u.right != None:
                      Q.append(u.right)
                      L.append(l+1)
      
                  # If there is a node still in the queue and all the nodes in the queue
                  # are at the same level, then increment the level and print.
                  if len(L) > 0 and L[0] > level and L[0] == L[-1]:
                      level += 1
                      print level, [x.key for x in Q]

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-16
        • 2010-11-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多