SortTree.py
#coding=utf-8
#二叉排序树
class TreeNode:
def __init__(self,data,left=None,right=None):
self.data=data
self.left=left
self.right=right
class SortTree:
def __init__(self):
self.root=None
def set_root(self,rootNode):
self.root=rootNode
def find(self,value):
Node=self.root
Node,flag=self.__find(value,Node,0)
return Node,flag
def __find(self,value,Node,num):
num+=1
if Node.left==None and Node.right==None and value!=Node.data:
print Node.data,'find error',num
return Node,False
elif valuereturn self.__find(value,Node.left,num)
elif value>Node.data:
return self.__find(value,Node.right,num)
elif value==Node.data:
print value,'find succeed',num
return Node,True
def insert(self,value):
Node,flag=self.find(value)
if flag==True:
print 'Had',value,'cannot insert'
else:
if value>Node:
Node.right=TreeNode(value)
else:
Node.left=TreeNode(value)
def __findP(self,value,Node,temp):
if Node.left==None and Node.right==None and value!=Node.data:
return Node,False
elif valuereturn self.__findP(value,Node.left,temp)
elif value>Node.data:
temp=Node
return self.__findP(value,Node.right,temp)
elif value==Node.data:
#print value,'find succeed'
return Node,temp,True
def delete(self,value):
temp=0
Node,Parent,flag=self.__findP(value,self.root,temp)
if flag==True:
#print Node.data,Parent.data,flag
if Node.left==None and Node.right==None:
if Parent.left==Node:
Parent.left=None
elif Parent.right==Node:
Parent.right=None
elif Node.left==None and Node.right!=None:
if Parent.left==Node:
Parent.left= Node.right
elif Parent.right==Node:
Parent.right= Node.right
elif Node.left!=None and Node.right==None:
if Parent.left==Node:
Parent.left= Node.left
elif Parent.right==Node:
Parent.right= Node.left
else:
#中序遍历前驱替换本节点的值
#删除中序前驱
res=self.list_all()
resV=[re.data for re in res]
var=res[resV.index(Node.data)-1].data
self.delete(var)
Node.data=var
res=self.list_all()
resV=[re.data for re in res]
print 'mid',resV
else:
print "error"
def list_all(self):
#中序遍历
lis=[]
res=[]
node = self.root
while lis or node:
while node:
lis.append(node)
node = node.left
#print node.data
if len(lis)>0:
node = lis[-1]
lis=lis[:-1]
if node:
res.append(node)
node= node.right
return res
test.py
#coding=utf-8
from SortTree import SortTree,TreeNode
def printL(tree):
res=tree.list_all()
resV=[re.data for re in res]
print 'mid',resV
n37=TreeNode(37)
n51=TreeNode(51)
n35=TreeNode(35,None,n37)
n47=TreeNode(47,n35,n51)
n58=TreeNode(58,n47,None)
n93=TreeNode(93)
n99=TreeNode(99,n93,None)
n73=TreeNode(73)
n88=TreeNode(88,n73,n99)
n62=TreeNode(62,n58,n88)
tree=SortTree()
tree.set_root(n62)
printL(tree)
tree.insert(95)
printL(tree)
#tree.delete(51)
tree.delete(99)
tree.delete(73)
tree.delete(47)
printL(tree)