Meta OA 面试真题解析:二叉树中距离目标节点 K 的所有节点

30次阅读
没有评论

Given a binary tree (pointer to the root), a target node anywhere in the tree, and an integer value K, return a list of the values of all the nodes that have a distance K from the target node. The order of the list does not matter.

Example:

print_tree(root, 3)
find_at_distance(root, 3, 2)
[2, 6, 7, 8]

这道题考察二叉树上的“距离 K 节点”查找,核心思路通常是先把目标节点到根节点的路径信息补全,再从目标节点向下或向上扩展搜索。由于普通二叉树只有子指针,没有父指针,常见做法是先 DFS 建立父节点映射,随后从目标节点出发做 BFS/DFS,并配合 visited 防止在父子之间来回重复访问。这样就能在 O(n) 级别内找到所有距离恰好为 K 的节点,示例中目标节点 3、K=2 的结果为 [2, 6, 7, 8]。

正文完
 0