如何实现二叉树?

140
哪种数据结构最适合在Python中实现二叉树?

6
这里有很多解决方案都在实现二叉搜索树,但问题要求实现二叉树。 - vikas mehta
也许在问题标题中指定你想要使用Python实现树算法? - Ken Tran
21个回答

-1

Python中的二叉树

 class Tree(object):
    def __init__(self):
        self.data=None
        self.left=None
        self.right=None
    def insert(self, x, root):
        if root==None:
            t=node(x)
            t.data=x
            t.right=None
            t.left=None
            root=t
            return root
        elif x<root.data:
            root.left=self.insert(x, root.left)
        else:
            root.right=self.insert(x, root.right)
        return root

    def printTree(self, t):
        if t==None:
            return

        self.printTree(t.left)
        print t.data
        self.printTree(t.right)

class node(object):
    def __init__(self, x):
        self.x=x

bt=Tree()
root=None
n=int(raw_input())
a=[]
for i in range(n):
    a.append(int(raw_input()))
for i in range(n):
    root=bt.insert(a[i], root)
bt.printTree(root)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接