LeetCode 题解工作台
二叉树寻路
在一棵无限的二叉树上,每个节点都有两个子节点,树中的节点 逐行 依次按 “之” 字形进行标记。 如下图所示,在奇数行(即,第一行、第三行、第五行……)中,按从左到右的顺序进行标记; 而偶数行(即,第二行、第四行、第六行…&hellip…
3
题型
4
代码语言
3
相关题
当前训练重点
中等 · 二分·树·traversal
答案摘要
对于一棵完全二叉树,第 行的节点个数为 ,第 行的节点编号范围为 $[2^{i-1}, 2^i - 1]$。而题目中对于奇数行,按从左到右的顺序进行标记,对于偶数行,按从右到左的顺序进行标记。所以对于第 行的节点 ,它的互补节点编号为 $2^{i-1} + 2^i - 1 - label$。所以节点 的实际父节点编号为 $(2^{i-1} + 2^i - 1 - label) / 2$。我…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·树·traversal 题型思路
题目描述
在一棵无限的二叉树上,每个节点都有两个子节点,树中的节点 逐行 依次按 “之” 字形进行标记。
如下图所示,在奇数行(即,第一行、第三行、第五行……)中,按从左到右的顺序进行标记;
而偶数行(即,第二行、第四行、第六行……)中,按从右到左的顺序进行标记。

给你树上某一个节点的标号 label,请你返回从根节点到该标号为 label 节点的路径,该路径是由途经的节点标号所组成的。
示例 1:
输入:label = 14 输出:[1,3,4,14]
示例 2:
输入:label = 26 输出:[1,2,6,10,26]
提示:
1 <= label <= 10^6
解题思路
方法一:数学
对于一棵完全二叉树,第 行的节点个数为 ,第 行的节点编号范围为 。而题目中对于奇数行,按从左到右的顺序进行标记,对于偶数行,按从右到左的顺序进行标记。所以对于第 行的节点 ,它的互补节点编号为 。所以节点 的实际父节点编号为 。我们可以通过不断地求互补节点编号和父节点编号,直到到达根节点,即可得到从根节点到节点 的路径。
最后,我们需要将路径反转,因为题目要求路径是从根节点到节点 的路径。
时间复杂度 ,其中 为节点 的编号。忽略答案的空间消耗,空间复杂度 。
class Solution:
def pathInZigZagTree(self, label: int) -> List[int]:
x = i = 1
while (x << 1) <= label:
x <<= 1
i += 1
ans = [0] * i
while i:
ans[i - 1] = label
label = ((1 << (i - 1)) + (1 << i) - 1 - label) >> 1
i -= 1
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for familiarity with binary-tree traversal concepts and efficient path construction.
- question_mark
Evaluate how well the candidate handles the zigzag labelling pattern and row direction reversal.
- question_mark
Assess the candidate's ability to optimize the solution with respect to time and space complexity.
常见陷阱
外企场景- error
Misunderstanding the zigzag labelling pattern, especially for even-numbered rows.
- error
Incorrectly calculating the parent node, leading to errors in the path construction.
- error
Not accounting for the fact that the problem asks for the path from the root to the given node, not the tree structure itself.
进阶变体
外企场景- arrow_right_alt
Determine the path for multiple target labels simultaneously.
- arrow_right_alt
Calculate the path for nodes in a binary tree with arbitrary labelling patterns.
- arrow_right_alt
Return the path for a node using a breadth-first search approach.