📅  最后修改于: 2023-12-03 15:39:40.959000             🧑  作者: Mango
在二叉树中,每一层都有中间节点,即左右子树节点数量相同的节点。本文将介绍如何利用BFS(广度优先搜索)算法找到每一层的中间节点。
def find_mid_node(root):
if not root:
return []
queue = [(root, 0)]
res = []
cur_layer = -1
cur_layer_nodes = []
while queue:
node, layer = queue.pop(0)
if layer > cur_layer:
mid = cur_layer_nodes[len(cur_layer_nodes)//2]
res.append(mid)
cur_layer_nodes = [node.val]
cur_layer = layer
else:
cur_layer_nodes.append(node.val)
if node.left:
queue.append((node.left, layer+1))
if node.right:
queue.append((node.right, layer+1))
mid = cur_layer_nodes[len(cur_layer_nodes)//2]
res.append(mid)
return res
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# 1
# / \
# 2 3
# / \ / \
# 4 5 6 7
# /
# 8
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
root.right.left = TreeNode(6)
root.right.right = TreeNode(7)
root.left.left.left = TreeNode(8)
print(find_mid_node(root)) # [1, 2, 5, 8]
本算法的时间复杂度为O(n),其中n为节点数。因为我们需要遍历每个节点一次,并将其加入队列中。而由于每个节点都只会被遍历一次,并且每个节点都只被加入队列中一次,所以时间复杂度为O(n)。