python实现二叉树

来源:互联网 发布:蓝牙兼容软件 编辑:程序博客网 时间:2024/06/05 11:55

这里我用python实现简单的二叉树,我实现的树在插入时会将原来的子树下降一阶

#-*- coding:utf-8 -*-#嵌套实现树#以r为根生成二叉树def newTree(r):    return [r,[],[]]def getRootVal(r):    return r[0]def setRootVal(r,newVal):    r[0] = newValdef getLeftChild(r):    return r[1]def getRightChild(r):    return r[2]def insertLeftChild(r,newBranch):    t = r.pop(1)    if len(t)>0:        root.insert(1,[newBranch,t,[]])    else:        root.insert(1,[newBranch,[],[]])def insertRightChild(r,newBranch):    t = r.pop(2)    if len(t)>0:        root.insert(2,[newBranch,[],t])    else:        root.insert(2,[newBranch,[],[]])root = newTree(5)setRootVal(root,6)print rootinsertLeftChild(root,5)insertRightChild(root,7)print rootinsertLeftChild(root,4)insertRightChild(root,8)print root#类实现二叉树class newTrees:    #初始化,即构造方法    def __init__(self,root):          self.root = root        self.leftChild = None        self.rightChild = None    #获取根值    def getRootVal(self):        return self.root    #设置根值    def setRootVal(self,newBranch):        self.root = newBranch    #获取左子树    def getLeft(self):        return self.leftChild    #获取右子树    def getRight(self):        return self.rightChild    #插入左子树    def insertLeft(self,newBranch):        if self.leftChild == None:            self.leftChild = newTrees(newBranch)        else:            t = newTrees(newBranch)            t.leftChild = self.leftChild            self.leftChild = t    #插入右子树    def inserRight(self,newBranch):        if self.rightChild == None:            self.rightChild = newTrees(newBranch)        else:            t = newTrees(newBranch)            t.rightChild = self.rightChild            self.rightChild = t    #先序遍历    def preorder(self):        print(self.root)        if self.leftChild:            self.leftChild.preorder()        if self.rightChild:            self.rightChild.preorder()    #中序遍历    def inoder(self):        if self.leftChild:            self.leftChild.inoder()        print self.root        if self.rightChild:            self.rightChild.inoder()    #后序遍历    def postorder(self):        if self.leftChild:            self.leftChild.postorder()        if self.rightChild:            self.rightChild.postorder()        print self.rootroot2 = newTrees(6)root2.insertLeft(5)root2.inserRight(7)root2.insertLeft(4)root2.inserRight(8)print u'先序遍历'root2.preorder()print u'中序遍历'root2.inoder()print u'后序遍历'root2.postorder()

结果
这里写图片描述