binary_tree.py
#coding: utf-8
import turtle
class Node(object):
def __init__(self,item):
self.elem=item
self.lchild=None
self.rchild=None
class binary_tree(object):
"""二叉树"""
def __init__(self):
self.root=None
def add(self,item):
# 使用队列完成广度优先遍历来添加元素
node =Node(item)
if self.root is None:
self.root=node
return
queue = [self.root]
while queue:
cur_node=queue.pop(0)
if cur_node.lchild is None:
cur_node.lchild=node
return
else:
queue.append(cur_node.lchild)
if cur_node.rchild is None:
cur_node.rchild=node
return
else:
queue.append(cur_node.rchild)
def breadth_travel(self):
"""广度优先遍历"""
if self.root is None:
return
queue=[self.root]
while queue:
cur_node=queue.pop(0)
print(cur_node.elem,end=' ')
if cur_node.lchild is not None:
queue.append(cur_node.lchild)
if cur_node.rchild is not None:
queue.append(cur_node.rchild)
def pre_order(self,node):
"""先序遍历"""
if node is None:
return
print(node.elem,end=' ')
self.pre_order(node.lchild)
self.pre_order(node.rchild)
def in_order(self,node):
"""中序遍历"""
if node is None:
return
self.pre_order(node.lchild)
print(node.elem, end=' ')
self.pre_order(node.rchild)
def post_order(self, node):
"""后序遍历"""
if node is None:
return
self.pre_order(node.lchild)
self.pre_order(node.rchild)
print(node.elem, end=' ')
def node_count(self,node):
"""二叉树节点个数"""
if node is None:
return 0
else:
return self.node_count(node.lchild) + self.node_count(node.rchild) + 1
def tree_depth1(self,node):
"""二叉树的深度(递归)"""
if node is None:
return 0
else:
return max(self.tree_depth1(node.lchild),self.tree_depth1(node.rchild))+1
def tree_depth2(self,node):
if node is None:
return None
result = 0
queue = [(node, 1)]
while queue:
temp_node, temp_layer = queue.pop(0)
if temp_node:
queue.append((temp_node.lchild, temp_layer + 1))
queue.append((temp_node.rchild, temp_layer + 1))
result = temp_layer + 1
return result - 1
if __name__ == "__main__":
tree=binary_tree()
tree.add(1)
tree.add(2)
tree.add(3)
tree.add(4)
tree.add(5)
tree.add(6)
tree.add(7)
tree.add(8)
tree.add(9)
tree.breadth_travel()
print('\t')
tree.pre_order(tree.root)
print('\t')
tree.in_order(tree.root)
print('\t')
tree.post_order(tree.root)
print('\t')
print(tree.node_count(tree.root))
print('\t')
print(tree.tree_depth1(tree.root))
print('\t')
print(tree.tree_depth2(tree.root))
binary_search_tree.py
#coding: utf-8
class Node(object):
def __init__(self,item,left=None,right=None):
self.elem=item
self.lchild=left
self.rchild=right
class BST(object):
"""二叉搜索树,排序树"""
def __init__(self,root=None):
self.root=root
def get(self,key):
"""查找节点"""
return self.__get(self.root,key)
def __get(self,node,key):
if node == None:
return None
if key == node.elem:
return node.elem
elif key < node.elem:
return self.__get(node.lchild,key)
else:
return self.__get(node.rchild,key)
def insert(self,value):
"""添加节点"""
self.root=self.__insert(self.root,value)
def __insert(self,node,value):
if node == None:
return Node(value)
if value == node.elem:
pass
elif value < node.elem:
node.lchild=self.__insert(node.lchild,value)
else:
node.rchild=self.__insert(node.rchild,value)
return node
def remove(self,key):
"""删除节点"""
self.root=self.__remove(self.root,key)
def __remove(self,node,key):
if node == None:
return None
if key < node.elem:
node.lchild=self.__remove(node.lchild,key)
elif key > node.elem:
node.rchild=self.__remove(node.rchild,key)
else:
if node.lchild == None:
node=node.rchild
elif node.rchild == None:
node=node.lchild
else:
node.elem=self.__getMax(node.lchild)
node.lchild=self.__remove(node.lchild,node.elem)
return node
def getMax(self):
"""获取全局最大值"""
return self.__getMax(self.root)
def __getMax(self,node):
"""获取局部最大值"""
if node == None:
return None
while node.rchild:
node=node.rchild
return node.elem
def preOrder(self,node):
"""先序遍历"""
if node == None:
return
print(node.elem,end=' ')
self.preOrder(node.lchild)
self.preOrder(node.rchild)
def inOrder(self,node):
"""中序遍历"""
#对二叉排序树的中序遍历可以得到递增的序列!
if node == None:
return
self.inOrder(node.lchild)
print(node.elem, end=' ')
self.inOrder(node.rchild)
if __name__ == "__main__":
bst=BST()
bst.insert(12)
bst.insert(20)
bst.insert(24)
bst.insert(5)
bst.insert(10)
bst.insert(15)
bst.insert(8)
bst.insert(6)
print(bst.get(6))
bst.inOrder(bst.root)
bst.remove(20)
print('\t')
bst.inOrder(bst.root)
binary_heap.py
#coding: utf-8
# encoding = utf-8
class heap(object):
"""小顶堆(便于Dijkstra算法)"""
def __init__(self):
'''
初始化一个空堆,使用数组来在存放堆元素,节省存储
'''
self.data_list = []
def get_parent_index(self, index):
'''
返回父节点的下标
'''
if index == 0 or index > len(self.data_list) - 1:
return None
else:
return (index - 1) >> 1
def swap(self, index_a, index_b):
'''
交换数组中的两个元素
'''
self.data_list[index_a], self.data_list[index_b] = self.data_list[index_b], self.data_list[index_a]
def insert(self, data):
'''
先把元素放在最后,然后从后往前依次堆化
这里以小顶堆为例,如果插入元素比父节点小,则交换,直到最后
'''
self.data_list.append(data)
index = len(self.data_list) - 1
parent = self.get_parent_index(index)
# 循环,直到该元素成为堆顶,或大于父节点(对于小顶堆)
while parent is not None and self.data_list[parent] > self.data_list[index]:
# 交换操作
self.swap(parent, index)
index = parent
parent = self.get_parent_index(parent)
def removeMax(self):
'''
删除堆顶元素,然后将最后一个元素放在堆顶,再从上往下依次堆化
'''
remove_data = self.data_list[0]
self.data_list[0] = self.data_list[-1]
del self.data_list[-1]
# 堆化
self.heapify(0)
return remove_data
def heapify(self, index):
'''
从上往下堆化,从index 开始堆化操作 (小顶堆)
'''
total_index = len(self.data_list) - 1
while True:
maxvalue_index = index
if 2 * index + 1 <= total_index and self.data_list[2 * index + 1] < self.data_list[maxvalue_index]:
maxvalue_index = 2 * index + 1
if 2 * index + 2 <= total_index and self.data_list[2 * index + 2] < self.data_list[maxvalue_index]:
maxvalue_index = 2 * index + 2
if maxvalue_index == index:
break
self.swap(index, maxvalue_index)
index = maxvalue_index
if __name__ == "__main__":
myheap = heap()
for i in range(10):
myheap.insert(i + 1)
print('建堆:', myheap.data_list)
print(myheap.removeMax())