二叉搜索树(BST)的Python实现

 1 import random
 2 class BST():
 3     left = None
 4     right = None
 5     data = None
 6     def __init__(self, data):
 7         self.data = data
 8 # 插入操作
 9 def BSTInsert(previous, root, value):
10     #root代表上一次的节点,previou代表要插入的节点的父母
11     #遍历到外层时,从19或20行的right或者left为空时,则新申请节点,插入到父母下面
12     if root is None:
13         if value > previous.data:#若大于双亲的值,则插入到父母右子树
14             previous.right = BST(value)
15         else :#否则,插入父母到左子树上
16             previous.left = BST(value)
17         return True
18     elif value==root.data:#和树中某个节点值相等,插入失败。因为BST要求 左<跟<右
19         return False
20     elif value > root.data:#继续深入递归,若value > 当前节点,转向右子树去递归。
21                            #直到root.right或者root.left节点为空,说明走到头了,此时转到11行,执行插入
22         return BSTInsert(root, root.right, value)
23     else: 
24         return BSTInsert(root, root.left, value)
25 #中序遍历
26 def InOrder(root):
27     if root is not None:
28         InOrder(root.left)
29         print(root.data)
30         InOrder(root.right)
31 #先序遍历
32 def PreOrder(root):
33     if root is not None:
34         print(root.data)
35         InOrder(root.left)
36         InOrder(root.right)
37 #后序遍历
38 def PostOrder(root):
39     if root is not None:
40         InOrder(root.left)
41         InOrder(root.right)
42         print(root.data)
43 
44 def BSTSearch(root, value):
45     if root is None:
46         return None
47     while root is not None:
48         if value > root.data:
49             root = root.right
50         elif value < root.data:
51             root = root.left
52         else:
53             return root
54     return None
55 #根节点10
56 root = BST(10)
57 #插入范围0到500的随机数
58 for i in range(100):
59     BSTInsert(None, root, random.randint(0,500))
60 #中遍历输出结果:从小到大
61 InOrder(root)
62 #搜索111的地址
63 print(BSTSearch(root, 111))

 

posted @ 2020-03-04 17:38  wkfxm  阅读(654)  评论(0编辑  收藏  举报