栈:stack 先进后出
队列:queue 先进先出
链表: linked list node+指针
实现
class Node:
'''
data: 节点保存的数据
_next: 保存下一个节点对象
'''
def __init__(self, data, pnext=None):
self.data = data
self._next = pnext
def __repr__(self):
'''
用来定义Node的字符输出,
print为输出data
'''
return str(self.data)
- 判断是否为空 2. 删除更新插入查找 3. 清空
图:graph 包含node和edge
# 图的节点结构
class Node:
def __init__(self, value):
self.value = value # 节点值
self.come = 0 # 节点入度
self.out = 0 # 节点出度
self.nexts = [] # 节点的邻居节点
self.edges = [] # 在节点为from的情况下,边的集合
class Edge:
def __init__(self, weight, fro, to):
self.weight = weight # 边的权重
self.fro = fro # 边的from节点
self.to = to # 边的to节点
class Graph:
def __init__(self):
self.nodes = {} # 图的所有节点集合 字典形式:{节点编号:节点}
self.edges = [] # 图的边集合
BFS(广度优先):取最近的子节点,一步步走出去。可使用队列实现
从root开始,遍历点,取出队列,将子节点放入队列,指导遍历完成。
import queue
def bfs(adj, start):
visited = set()
q = queue.Queue()
q.put(start) #把起始点放入队列
while not q.empty():
u = q.get()
print(u)
for v in adj.get(u, []):
if v not in visited:
visited.add(v)
q.put(v)
graph = {1: [4, 2], 2: [3, 4], 3: [4], 4: [5]}
bfs(graph, 1)
DFS(深度优先):沿着一条路走到头再走另一条路(子节点亦如此)
使用栈实现。根节点的子节点压入栈中,pop左子节点再压入其子节点。直到栈空。
非递归实现:
def dfs(adj, start):
visited = set()
stack = [[start, 0]]
while stack:
(v, next_child_idx) = stack[-1]
if (v not in adj) or (next_child_idx >= len(adj[v])):
stack.pop()
continue
next_child = adj[v][next_child_idx]
stack[-1][1] += 1
if next_child in visited:
continue
print(next_child)
visited.add(next_child)
stack.append([next_child, 0])
graph = {1: [4, 2], 2: [3, 4], 3: [4], 4: [5]}
dfs(graph, 1)
树:
二叉搜索树:
def insert(self, root, val):
'''二叉搜索树插入操作'''
if root == None:
root = TreeNode(val)
elif val < root.val:
root.left = self.insert(root.left, val)
elif val > root.val:
root.right = self.insert(root.right, val)
return root
搜索O(log2N~N),从根节点开始
删除:以右子树最小节点替代(判断左右是否有子节点)
插入:比较根节点后小左大右
平衡二叉树:平衡二叉树定义为:二叉树中任意结点的左右子树深度差不超过1.递归判断(DFS)
B树
B+树
avl树(平衡二叉树)
红黑树
!!!!!!(后续补充)
hash table(略)