https://leetcode.com/problems/path-in-zigzag-labelled-binary-tree/
In an infinite binary tree where every node has two children, the nodes are labelled in row order.
In the odd numbered rows (ie., the first, third, fifth,...), the labelling is left to right, while in the even numbered rows (second, fourth, sixth,...), the labelling is right to left.
Given the label
of a node in this tree, return the labels in the path from the root of the tree to the node with that label
.
Example 1:
Input: label = 14 Output: [1,3,4,14]
Example 2:
Input: label = 26 Output: [1,2,6,10,26]
Constraints:
1 <= label <= 10^6
算法思路:
奇数行顺序和正常的顺序一致
偶数行顺序和正常的顺序是倒置的
隔代相除得到祖父节点,这是具有一般性的(和数组实现的堆中求节点的根一样),所以主要任务就是求label的根节点previous,根据上一层的位置置换原则,也就是相对位置不变,正常顺序中previous到end的距离,对应实际start到prevoius的距离(对称原则)。label的前一行start和end在正常的顺序中的位置是很好计算的。有点难度,不是很容易想到,即使想到,相对关系也得注意不能弄错。
class Solution {
public:
vector<int> pathInZigZagTree(int label) {
if (label == 1) return {1};
int i = 2;
while (i <= label) i *= 2;
vector<int> res;
res.push_back(label);
label /= 2;
int end = i / 2 - 1;
int start = i / 4;
int previous = start + end - label;
int flag = 1;
res.push_back(previous);
while (label > 1 && previous > 1) {
label /= 2;
previous /= 2;
if (flag % 2) res.push_back(label);
else res.push_back(previous);
flag++;
}
reverse(res.begin(), res.end());
return res;
}
};
有时间画个图传上来