堆(python操作)
import heapq
class Test:
def test(self):
# 创建最小堆
minheap = []
heapq.heapify(minheap)
#增加元素
heapq.heappush(minheap,10);
heapq.heappush(minheap,5);
heapq.heappush(minheap,7);
heapq.heappush(minheap,6);
heapq.heappush(minheap,1);
heapq.heappush(minheap,11);
heapq.heappush(minheap,3);
print(minheap)
#打印堆顶数
print(minheap[0])
#delete
heapq.heappop(minheap)
print(len(minheap))
lin_test = Test()
lin_test.test()
BFS(层序遍历)
#####层序遍历的套路代码(leetcode 102、107、116、117题均可用该模板)
dq = deque([]) #新建一个队列
dq.append(root)#把根节点加入到队列中
while len(dq) > 0:
size = len(dq)
res = [] #新建一个列表来保存每一层的元素
for _ in range(size):
node = dq.popleft()
res.append(node)
if node.left:#如果该节点有左子树,将其加入到dq中。这里就是递归的思想了。
dq.append(node.left)
if node.right:
dq.append(node.right)
##### 现在res里面存了同层的节点,开始设置指针(116题和117题用到。102、107不需要)
for i in range(len(res) - 1):
res[i].next = res[i + 1]
res[-1].next = None
return root