简体   繁体   English

如何逐级打印二叉树

[英]How can I print a binary tree level by level

How would you print out the data in a binary tree, level by level, starting at the top, with python? 您将如何使用python从顶部开始逐级打印二进制树中的数据?

I'm very new with this and I don't have any idea how to start. 我对此很陌生,我也不知道如何开始。

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)

You can think of printing a binary tree level-by-level as a breadth-first search of the tree beginning at the root. 您可以将逐级打印二叉树看作是从根开始的广度优先搜索。 In a breadth-first search, you explore all the nodes at distance one from the root before the nodes at distance two, and the nodes at distance two from the root before the nodes at distance three, etc. 在广度优先搜索中,您探索距离根一号的所有节点,距离二号的节点之前的所有节点,以及距离根二号的距离,距离三号节点之前的所有节点,等等。

I actually don't know any Python programming, but the pseudocode for this algorithm is quite simple. 我实际上不知道任何Python编程,但是此算法的伪代码非常简单。 Given that Python is essentially executable pseudocode, I can't imagine it being that difficult to convert this into legal 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.

Hope this helps! 希望这可以帮助! And apologies for the lack of real code; 对于缺乏真实代码表示歉意; learning Python is still on my TODO list. 学习Python仍在我的TODO列表中。

Try using recursion for this. 尝试为此使用递归。 If you use the base condition that the tree is empty, you can simply say something like: 如果使用树为空的基本条件,则可以简单地说:

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

The idea here being to call the function on the left and the right branches of the tree and append them to a result including the root of the tree that you're in. If the tree has an empty branch, the function will append an empty string and "keep rolling." 这里的想法是在树的左右分支上调用函数,并将它们附加到包含您所在树的根的结果中。如果树上有一个空分支,则函数将在后面附加一个空字符串和“保持滚动”。

Here is some code that will print a binary tree by level. 这是一些将按级别打印二叉树的代码。 I used a different class definition though. 我虽然使用了不同的类定义。

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM