二叉搜索树即左孩子<=根节点,右孩子>=根节点
# -*- coding: utf-8 -*-
class TreeNode:
def __init__(self,value):
self.value=value
self.left=None
self.right=None
class bst_Method:
def tree_Create(self,root,val):
if root==None:
root=TreeNode(val)
elif val<root.value:
root.left=self.tree_Create(root.left,val)
elif val>root.value:
root.right=self.tree_Create(root.right,val)
return root
def tree_Query(self,root,val):
if root==None:
return
if root.value==val:
return root.value
elif root.value>val:
return self.tree_Query(root.left,val)
elif root.value>val:
return self.tree_Query(root.right,val)
def delNode(self, root, val):
'''删除二叉搜索树中值为val的点'''
if root == None:
return
if val < root.value:
root.left = self.delNode(root.left, val)
elif val > root.value:
root.right = self.delNode(root.right, val)
# 当val == root.val时,分为三种情况:只有左子树或者只有右子树、有左右子树、即无左子树又无右子树
else:
if root.left and root.right:
# 既有左子树又有右子树,则需找到右子树中最小值节点
temp = self.find_Min(root.right)
root.value = temp.value
# 再把右子树中最小值节点删除
root.right = self.delNode(root.right, temp.value)
elif root.right == None and root.left == None:
# 左右子树都为空
root = None
elif root.right == None:
# 只有左子树
root = root.left
elif root.left == None:
# 只有右子树
root = root.right
return root
def find_Min(self,root):
if root.left:
return self.find_Min(root.left)
else:
return root
def find_Max(self,root):
if root.right:
return self.find_Max(root.right)
else:
return root
def tree_Print(self,root):
if root==None:
return
self.tree_Print(root.left)
print(root.value,end=' ')
self.tree_Print(root.right)
if __name__=='__main__':
List = [17, 5, 35, 2, 11, 29, 38, 9, 16, 8]
root=None
op=bst_Method()
for i in List:
root=op.tree_Create(root,i)
print('中序遍历,二叉搜索树的中序遍历是有序的')
op.tree_Print(root)
print('')
print('根节点的值为:', root.value)
print('树中最大值为:', op.find_Max(root).value)
print('树中最小值为:', op.find_Min(root).value)
print('查询树中值为5的节点:', op.tree_Query(root, 5))
print('查询树中值为100的节点:', op.tree_Query(root, 100))
print('删除树中值为16的节点:', end=' ')
root = op.delNode(root, 16)
op.tree_Print(root)
print('')
print('删除树中值为5的节点:', end=' ')
root = op.delNode(root, 5)
op.tree_Print(root)
print('')