以嵌套形式输出BST

时间:2014-11-09 06:15:33

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

我必须在BST中执行inOrder,levelOrder,preOrder和postOrder横向。

这是一个按顺序的小样本

class BSTNode:
    def __init__ (self, x, L=None, R=None):
        self.data = x
        self.left = L
        self.right = R

class BST:
    def __init__ (self):
        self.root = None

    def insert (self, x):
        def recurse (p):
            if x<p.data:
                if p.left==None:
                    p.left = BSTNode (x)
                else:
                    recurse (p.left)
            else:
                if p.right==None:
                    p.right = BSTNode (x)
                else:
                    recurse (p.right)
        if self.root==None:
            self.root = BSTNode(x)
        else:
            recurse (self.root)

    def inOrder (self):
        print ("InOrder:    ", end="")
        def recurse(node):
            if node != None:
                recurse(node.left)
                print(node.data,end = " ")
                recurse(node.right)
        recurse(self.root)
        print( )

def main( ):
    T = BST( )
    L = eval(input ("Enter list: "))
    for x in L:
        T.insert(x)
    T.inOrder( )

if __name__ == '__main__':
    main( )

有谁知道我应该怎么做?我现在为每次遍历都有单独的方法(Python),我正在使用队列进行级别顺序算法。

1 个答案:

答案 0 :(得分:1)

像在BST.inOrder中那样递归,但不是打印它们,而是递归地生成(并返回)一个列表。将重复函数放在BSTNode中似乎更有意义。

class BSTNode:
    def __init__(self, x, L=None, R=None):
        self.data = x
        self.left = L
        self.right = R

    def inOrder(self):
        ret = []
        if self.left: ret.append(self.left.inOrder())
        ret.append(self.data)
        if self.right: ret.append(self.right.inOrder())
        return ret

    def preOrder(self):
        ret = []
        ret.append(self.data)
        if self.left: ret.append(self.left.preOrder())
        if self.right: ret.append(self.right.preOrder())
        return ret

    def postOrder(self):
        ret = []
        if self.left: ret.append(self.left.postOrder())
        if self.right: ret.append(self.right.postOrder())
        ret.append(self.data)
        return ret

class BST:
    def __init__(self):
        self.root = None

    def insert(self, x):
        def recurse(p):
            if x<p.data:
                if p.left==None:
                    p.left = BSTNode(x)
                else:
                    recurse(p.left)
            else:
                if p.right==None:
                    p.right = BSTNode(x)
                else:
                    recurse(p.right)
        if self.root==None:
            self.root = BSTNode(x)
        else:
            recurse(self.root)

T = BST( )
for x in [5,3,7,2,4,6,8]:
    T.insert(x)
print(T.root.inOrder())
print(T.root.preOrder())
print(T.root.postOrder())

输出:

[[[2], 3, [4]], 5, [[6], 7, [8]]]
[5, [3, [2], [4]], [7, [6], [8]]]
[[[2], [4], 3], [[6], [8], 7], 5]

我会为你的练习留下Level-Order遍历。