二叉查找树的实现(using Python)----代码更加简单 wangsc

下面的代码实现了算法导论书中BST(Binary Search Tree)所列出的所有功能:
中序遍历,查找,最大/最小关键字元素,前趋和后继,插入和删除


Pyhon 实现的二叉查找树比C语言实现的一般会少一般的代码量,可能是因为Python语言本身设计时就是为了方便实现算法,基本上就是按照算法敲代码就可以了,C语言实现可能需要更多的考虑数据结构之间的接口衔接。


class node :
	def __init__(self,date):
		self.date=date
		self.p = None
		self.lchild = None
		self.rchild = None

def tree_insert(root,z):
	y = None
	x = root
	while x is not None :
		y = x
		if z.date<x.date:
			x = x.lchild
		else:
			x = x.rchild
	z.p=y
	if y==None:
		root = z
	else:
		if z.date<y.date:
			y.lchild=z
		else:
			y.rchild=z

def tree_inorder_walk(x):
	if x is not None:
		tree_inorder_walk(x.lchild)
		print x.date," "
		tree_inorder_walk(x.rchild)

def tree_search(x,key):
	while (x is not None) and (x.date!=key) :
		if key<x.date:
			x=x.lchild
		else:
			x=x.rchild
	return x

def tree_min(x):
	while x.lchild is not None:
		x=x.lchild
	return x

def tree_max(x):
	while x.rchild is not None:
		x=x.rchild
		return x

def tree_successor(x):
	if x.rchild is not None:
		return tree_min(x.rchild)
	y=x.p
	while (y is not None) and (x==x.rchild):
		x=y
		y=y.p
	return y

def tree_delete(root,z):
	if (z.lchild is not None) or (z.rchild is None):
		y=z
		y=tree_successor(z)
	if y.lchild is not None:
		x=y.lchild
	else:
		x=y.rchild
	if x is not None:
		x.p=y.p
	if y.p is None:
		root=x
	else:
		if y==y.p.lchild:
			y.p.lchild=x
		else:
			y.p.rchild=x
	if y!=z:
		z.date=y.date
	return y

root=node(12)
lst=[5,8,18]
for a in lst:
	z=node(a)
	tree_insert(root,z)
tree_inorder_walk(root)
x=tree_search(root,8)
print "there is a ",x.date," in the tree"
x=tree_max(root)
print "the max num of this tree is: ",x.date
x=tree_min(root)
print "the min num of this tree is: ",x.date
x=root.rchild
tree_delete(root,x)
print "after we delete the max num 18, the max num of this tree is: ",x.date

创建的树输入序列是12,5,8,18 ;大家可以根据BST性质画出图

 然后运行结果:前4个数是中序遍历结果,然后查找。然后最大最小关键字,最后是删除最大数18后,再次输出最大关键字,来验证删除是否成功。





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值