二叉搜索树

二叉搜索树(Binary Search Tree)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key


def insert(root, key):
if root is None:
return Node(key)
else:
if root.val == key:
return root
elif root.val < key:
root.right = insert(root.right, key)
else:
root.left = insert(root.left, key)
return root


def inorder(root):
if root:
inorder(root.left)
print(root.val)
inorder(root.right)


def min_value_node(node):
current = node
while current.left is not None:
current = current.left
return current


def delete_node(root, key):
if root is None:
return root
if key < root.key:
root.left = delete_node(root.left, key)
elif key > root.key:
root.right = delete_node(root.right, key)
else:
if root.left is None:
temp = root.right
root = None
return temp
elif root.right is None:
temp = root.left
root = None
return temp
temp = min_value_node(root.right)
root.key = temp.key
root.right = delete_node(root.right, temp.key)
return root


def search(root, key):
if root is None:
return None
if key > root.val:
return search(root.right, key)
elif key < root.val:
return search(root.left, key)
else:
return root

二叉搜索树
https://wangqian0306.github.io/2021/binary_search_tree/
作者
WangQian
发布于
2021年11月18日
许可协议