目录
1.树与二叉树
2.树的实例:模拟文件系统
3.二叉树
4.二叉树的遍历
5.二叉搜索树
5.1插入
5.2查询
5.3删除
1.树与二叉树
2.树的实例:模拟文件系统
# 树的实例
class Node:
def __init__(self, name, type='dir'):
self.name = name
self.type = type # type = "dir" or "file"
self.children = []
self.parent = None
def __repr__(self):
return self.name
class FileSystemTree:
def __init__(self):
self.root = Node("/") # .../abc/123.txt
self.now = self.root
def mkdir(self, name):
# name 以 / 结尾
if name[-1] != "/":
name += "/"
node = Node(name)
self.now.children.append(node)
node.parent = self.now
def ls(self):
return self.now.children
def cd(self, name):
if name[-1] != "/":
name += "/"
for child in self.now.children:
if child.name == name:
self.now = child
return
raise ValueError("invalid dir")
tree = FileSystemTree()
tree.mkdir("var/")
tree.mkdir("bin/")
tree.mkdir("usr/")
tree.cd("bin/")
tree.mkdir("python/")
print(tree.ls())
# print(tree.root.children)
3.二叉树
class BiTreeNode:
def __init__(self, data):
self.data = data
self.lchild = None
self.rchild = None
a = BiTreeNode("A")
b = BiTreeNode("B")
c = BiTreeNode("C")
d = BiTreeNode("D")
e = BiTreeNode("E")
f = BiTreeNode("F")
g = BiTreeNode("G")
e.lchild = a
e.rchild = g
a.rchild = c
c.lchild = b
c.rchild = d
g.rchild = f
root = e
print(root.lchild.rchild.data)
4.二叉树的遍历
from collections import deque
class BiTreeNode:
def __init__(self, data):
self.data = data
self.lchild = None
self.rchild = None
a = BiTreeNode("A")
b = BiTreeNode("B")
c = BiTreeNode("C")
d = BiTreeNode("D")
e = BiTreeNode("E")
f = BiTreeNode("F")
g = BiTreeNode("G")
e.lchild = a
e.rchild = g
a.rchild = c
c.lchild = b
c.rchild = d
g.rchild = f
root = e
# print(root.lchild.rchild.data)
def pre_order(root):
'''前序遍历'''
if root:
print(root.data, end=',')
pre_order(root.lchild)
pre_order(root.rchild)
def in_order(root):
if root:
in_order(root.lchild)
print(root.data, end=',')
in_order(root.rchild)
def post_order(root):
if root:
post_order(root.lchild)
post_order(root.rchild)
print(root.data, end=',')
def level_order(root):
queue = deque()
queue.append(root)
while len(queue) > 0: # 只要队列不空
node = queue.popleft()
print(node.data, end=',')
if node.lchild:
queue.append(node.lchild)
if node.rchild:
queue.append(node.rchild)
pre_order(root)
print()
in_order(root)
print()
post_order(root)
print()
level_order(root)
5.二叉搜索树
5.1插入
import random
class BiTreeNode:
'''节点'''
def __init__(self, data):
self.data = data
self.lchild = None
self.rchild = None
self.parenet = None
class Bst:
'''二叉搜索树'''
def __init__(self, li):
self.root = None
if li:
for val in li:
self.insert_not_recall(val=val)
def insert(self, node, val):
'''插入操作——递归的写法'''
if not node:
node = BiTreeNode(val)
elif val < node.data:
node.lchild = self.insert(node.lchild, val)
node.lchild.parenet = node
elif val > node.data:
node.rchild = self.insert(node.rchild, val)
node.rchild.parenet = node
return node
def insert_not_recall(self, val):
'''插入操作——非递归写法'''
p = self.root
if not p: # 空树
self.root = BiTreeNode(val)
return
while True:
if val < p.data:
if p.lchild:
p = p.lchild
else: # 左孩子不存在
p.lchild = BiTreeNode(val)
p.lchild.parenet = p
return
elif val > p.data:
if p.rchild:
p = p.rchild
else:
p.rchild = BiTreeNode(val)
p.rchild.parenet = p
return
else:
return
def pre_order(self, root):
'''前序遍历'''
if root:
print(root.data, end=',')
self.pre_order(root.lchild)
self.pre_order(root.rchild)
def in_order(self, root):
'''中序遍历'''
if root:
self.in_order(root.lchild)
print(root.data, end=',')
self.in_order(root.rchild)
def post_order(self, root):
'''后序遍历'''
if root:
self.post_order(root.lchild)
self.post_order(root.rchild)
print(root.data, end=',')
li = list(range(100))
random.shuffle(li)
tree = Bst(li=[4, 6, 7, 9, 2, 1, 3, 5, 8])
tree.pre_order(tree.root)
print()
tree.post_order(tree.root)
print()
tree.in_order(tree.root)
print()
#-----------------------------------------
tree = Bst(li=li)
tree.pre_order(tree.root)
print()
tree.post_order(tree.root)
print()
tree.in_order(tree.root)
结果:
4,2,1,3,6,5,7,9,8,
1,3,2,5,8,9,7,6,4,
1,2,3,4,5,6,7,8,9,
19,2,1,0,5,3,4,14,10,7,6,8,9,11,13,12,16,15,18,17,28,25,24,22,21,20,23,26,27,49,34,33,30,29,32,31,36,35,48,44,38,37,42,40,39,41,43,45,46,47,76,62,55,52,51,50,54,53,61,56,59,58,57,60,66,64,63,65,75,74,69,68,67,73,71,70,72,83,80,78,77,79,81,82,96,89,85,84,87,86,88,92,91,90,95,93,94,99,98,97,
0,1,4,3,6,9,8,7,12,13,11,10,15,17,18,16,14,5,2,20,21,23,22,24,27,26,25,29,31,32,30,33,35,37,39,41,40,43,42,38,47,46,45,44,48,36,34,50,51,53,54,52,57,58,60,59,56,61,55,63,65,64,67,68,70,72,71,73,69,74,75,66,62,77,79,78,82,81,80,84,86,88,87,85,90,91,94,93,95,92,89,97,98,99,96,83,76,49,28,19,
0,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,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,
Process finished with exit code 0
Note:
- 从二叉搜索树中序遍历可以看出,结果是有序的(升序)
5.2查询
def query(self, node, val):
'''查询——递归'''
if not node:
return None
if node.data < val:
return self.query(node.rchild, val)
elif node.data > val:
return self.query(node.lchild, val)
else:
return node
def query_not_recall(self, val):
'''查找——非递归'''
# p指向根节点
p = self.root
while p:
if p.data < val:
# p指向右孩子
p = p.rchild
elif p.data > val:
p = p.lchild
else:
return p
return None
5.3删除
- 如果要删除的节点是叶子结点:直接删除
- 如果要删除的节点只有一个孩子:将此节点的父亲与孩子节点连接,然后删除节点
- 如果要删除的节点有两个孩子:将其右子树的最小节点(该节点最多有一个右孩子)删除,并替换当前节点。(如图)
def __remove_node_1(self, node):
''' 情况1:已知node是叶子结点并且删除它'''
if not node.parenet: # 判断根节点
self.root = None
if node == node.parenet.lchild: # 判断node是否是它父亲的左孩子
node.parenet.lchild = None
else: # 否则删掉右孩子
node.parenet.rchild = None
def __remove_node2_1(self, node):
'''情况2-1:已知node只有一个左孩子'''
if not node.parenet: # 根节点(删除的节点如果没有父节点,那么根节点为它的左孩子节点)
self.root = node.lchild
node.parenet.lchild = None
elif node == node.parenet.lchild:
node.parenet.lchild = node.lchild
node.lchild.parenet = node.parenet
else:
node.parenet.rchild = node.lchild
node.lchild.parenet = node.parenet
def __remove_node2_2(self, node):
'''情况2-2:已知node只有一个右孩子'''
if not node.parenet:
self.root = node.rchild
elif node == node.parenet.lchild:
node.parenet.lchild = node.rchild
node.rchild.parenet = node.parenet
else:
node.parenet.rchild = node.rchild
node.rchild.parenet = node.parenet
def delete(self, val):
if self.root: # 先判断是不是空树
node = self.query_not_recall(val)
if not node: # 树中不存在这个val
return False
if not node.lchild and not node.rchild: # 情况1:叶子结点
self.__remove_node_1(node)
elif not node.rchild: # 2-1情况:没有右孩子
self.__remove_node2_1(node)
elif not node.lchild: # 2-2情况:没有左孩子
self.__remove_node2_2(node)
else: # 3.两个孩子都有
min_node = node.rchild
while min_node.lchild:
min_node = min_node.lchild
node.data = min_node.data
# delete min_node
if min_node.rchild:
self.__remove_node2_2(min_node)
else:
self.__remove_node_1(min_node)
node.rchild.parenet = node.parenet
整体代码:
import random
class BiTreeNode:
'''节点'''
def __init__(self, data):
self.data = data
self.lchild = None
self.rchild = None
self.parenet = None
class Bst:
'''二叉搜索树'''
def __init__(self, li):
self.root = None
if li:
for val in li:
self.insert_not_recall(val=val)
def insert(self, node, val):
'''插入操作——递归的写法'''
if not node:
node = BiTreeNode(val)
elif val < node.data:
node.lchild = self.insert(node.lchild, val)
node.lchild.parenet = node
elif val > node.data:
node.rchild = self.insert(node.rchild, val)
node.rchild.parenet = node
return node
def insert_not_recall(self, val):
'''插入操作——非递归写法'''
p = self.root
if not p: # 空树
self.root = BiTreeNode(val)
return
while True:
if val < p.data:
if p.lchild:
p = p.lchild
else: # 左孩子不存在
p.lchild = BiTreeNode(val)
p.lchild.parenet = p
return
elif val > p.data:
if p.rchild:
p = p.rchild
else:
p.rchild = BiTreeNode(val)
p.rchild.parenet = p
return
else:
return
def query(self, node, val):
'''查询——递归'''
if not node:
return None
if node.data < val:
return self.query(node.rchild, val)
elif node.data > val:
return self.query(node.lchild, val)
else:
return node
def query_not_recall(self, val):
'''查找——非递归'''
# p指向根节点
p = self.root
while p:
if p.data < val:
# p指向右孩子
p = p.rchild
elif p.data > val:
p = p.lchild
else:
return p
return None
def __remove_node_1(self, node):
''' 情况1:已知node是叶子结点并且删除它'''
if not node.parenet: # 判断根节点
self.root = None
if node == node.parenet.lchild: # 判断node是否是它父亲的左孩子
node.parenet.lchild = None
else: # 否则删掉右孩子
node.parenet.rchild = None
def __remove_node2_1(self, node):
'''情况2-1:已知node只有一个左孩子'''
if not node.parenet: # 根节点(删除的节点如果没有父节点,那么根节点为它的左孩子节点)
self.root = node.lchild
node.parenet.lchild = None
elif node == node.parenet.lchild:
node.parenet.lchild = node.lchild
node.lchild.parenet = node.parenet
else:
node.parenet.rchild = node.lchild
node.lchild.parenet = node.parenet
def __remove_node2_2(self, node):
'''情况2-2:已知node只有一个右孩子'''
if not node.parenet:
self.root = node.rchild
elif node == node.parenet.lchild:
node.parenet.lchild = node.rchild
node.rchild.parenet = node.parenet
else:
node.parenet.rchild = node.rchild
node.rchild.parenet = node.parenet
def delete(self, val):
if self.root: # 先判断是不是空树
node = self.query_not_recall(val)
if not node: # 树中不存在这个val
return False
if not node.lchild and not node.rchild: # 情况1:叶子结点
self.__remove_node_1(node)
elif not node.rchild: # 2-1情况:没有右孩子
self.__remove_node2_1(node)
elif not node.lchild: # 2-2情况:没有左孩子
self.__remove_node2_2(node)
else: # 3.两个孩子都有
min_node = node.rchild
while min_node.lchild:
min_node = min_node.lchild
node.data = min_node.data
# delete min_node
if min_node.rchild:
self.__remove_node2_2(min_node)
else:
self.__remove_node_1(min_node)
def pre_order(self, root):
'''前序遍历'''
if root:
print(root.data, end=',')
self.pre_order(root.lchild)
self.pre_order(root.rchild)
def in_order(self, root):
'''中序遍历'''
if root:
self.in_order(root.lchild)
print(root.data, end=',')
self.in_order(root.rchild)
def post_order(self, root):
'''后序遍历'''
if root:
self.post_order(root.lchild)
self.post_order(root.rchild)
print(root.data, end=',')
li = list(range(100))
random.shuffle(li)
tree = Bst(li=[4, 6, 7, 9, 2, 1, 3, 5, 8])
tree.pre_order(tree.root)
print()
tree.post_order(tree.root)
print()
tree.in_order(tree.root)
print()
# -------------------插入----------------------
tree = Bst(li=li)
tree.pre_order(tree.root)
print()
tree.post_order(tree.root)
print()
tree.in_order(tree.root)
# -------------------查询----------------------
li1 = list(range(10))
random.shuffle(li1)
tree1 = Bst(li=li1)
print()
print(tree1.query_not_recall(4).data)