以级别迭代打印二叉树的级别

时间:2014-03-19 20:13:44

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

我希望迭代地逐级打印二叉树,而不使用除了python列表之外的dequeue或任何其他数据结构。我已经在网上看过,大多数是上面提到的那种方式之一。

如果我有一棵树:

    41
   /  \
  7   53
 / \  /
1  19 47

我希望它打印如下:

41

7
53

1
19
47

这是我拍摄的,但它并没有打印出bst中的所有值:

def levelorder(self):

        current = self._root
        current_left = current_right = self._root
        a = [current._value]

        while current_left is not None and current_right is not None:

            current_left = current_left._left
            current_right = current_right._right

            if current_left is not None:
                a.append(current_left._value)

            if current_right is not None:
                a.append(current_right._value)

        return a

这是它输出的内容:

[41, 7, 53, 1]

任何想法我的代码有什么问题?以及如何解决这个问题?

TREE CLASS:

class _BSTNode:

    def __init__(self, value):

        self._value = copy.deepcopy(value)
        self._left = None
        self._right = None
        self._height = 1
        return

class BST:

    def __init__(self):

        self._root = None
        self._count = 0
        self.comparisons = 0
        return

    def levelorder(self):


        levels = [[self._root]]

        while levels[-1]:

            nextlevel = []
            for node in levels[-1]:
                nextlevel.extend([node for node in (node._left, node._right) if node])

            levels.append(nextlevel)
        return levels[:-1]

和我的主要部分:

b = BST()
b.insert(41)
b.insert(7)
b.insert(53)
b.insert(1)
b.insert(19)
b.insert(47)

print (b.levelorder())

1 个答案:

答案 0 :(得分:0)

没有测试,因为我没有你的Tree课程,但我希望一般的想法适用:

def levelorder(tree):
    levels = [ [tree.root] ]
    while levels [-1]:
        nextLevel = []
        for node in levels [-1]:
            nextLevel.extend ( [node for node in (node.left, node.right) if node] )
        levels.append (nextLevel)
    return levels # or maybe levels [:-1]

完全正常的例子:

#! /usr/bin/python3

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

    def __repr__(self):
        return self.payload

class Tree:
    def __init__(self, root):
        self.root = root

    def levels(self):
        levels = [[self.root]]
        while levels[-1]:
            nextLevel = []
            for node in levels[-1]:
                nextLevel.extend([node for node in (node.left, node.right) if node])
            levels.append(nextLevel)
        return levels[:-1]

t = Tree(Node('41', Node('7', Node('1'), Node('19')), Node('53', Node('47'))))

print(t.levels())

输出为[[41], [7, 53], [1, 19, 47]]