开发者

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?

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__(开发者_如何学JAVAself):
        """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. Given that Python is essentially executable pseudocode, I can't imagine it being that difficult to convert this into legal 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.


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]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜