Python 构造二叉搜索树

来源:互联网 发布:抓取网页数据工具 编辑:程序博客网 时间:2024/05/18 04:37

本文采用Python语言编写数据结构之二叉搜索树,主要实现二叉树的构造,插入数据,删除数据,以及二叉树的中序遍历,先序遍历,和后序遍历。
具体代码如下:

#构造二叉树结构,及属性class Tree(object):    def __init__(self):        self.root=Noneclass Node(object):    def __init__(self,x):        self.key=x        self.left=None        self.right=None        self.parent=None#插入二叉树数据def TreeInsert( T, z):    y =None    x = T.root    while x != None:        y = x        if z.key < x.key:            x = x.left        else:            x = x.right    z.parent = y    if y == None:        T.root = z    elif z.key < y.key:        y.left = z    else:        y.right = z    z.left = None    z.right = None    return z.key#删除节点def Transplant(T,u,v):    if u.parent==None:        T.root=v    elif u==u.parent.left:        u.parent.left=v    else:        u.parent.right=v    if v!=None:        v.parent=u.parentdef TreeMin(x):    while x.left !=None:        x=x.left    return xdef TreeDelete(T,z):    if z.left==None:        Transplant(T,z,z.right)    elif z.right==None:        Transplant(T,z,z.left)    else:        y=TreeMin(z.right)        if y.parent!=z:            Transplant(T,y,y.right)            y.right=z.right            y.right.parent=y        Transplant(T,z,y)        y.left=z.left        y.left.parent=y    return z.key#中序遍历def Midsort(root):    if root!= None:        Midsort(root.left)        if root.key!=0:            print(root.key)        Midsort(root.right)#先序遍历def Behsort(root):    if root!= None:        Behsort(root.left)        Behsort(root.right)        if root.key != 0:            print(root.key)#后序遍历def Presort(root):    if root!= None:        if root.key != 0:            print(root.key)        Presort(root.left)        Presort(root.right)#构造二叉树实例对象node=[5,9,6,8,7,2,1,10]T=Tree()#插入二叉树数据for nodes in node:    print('插入数据',TreeInsert(T,Node(nodes)))#删去一个节点print('删去节点',TreeDelete(T,T.root))#中序遍历print('中序遍历')Midsort(T.root)#后序遍历print('后序遍历')Behsort(T.root)#先序遍历print('先序遍历')Presort(T.root)

运行结果如下:
这里写图片描述