# 1104. 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`

``````class Solution {
public:
vector<int> pathInZigZagTree(int label) {
int level = 0, cur = label;
while (1 << level <= label) ++level;
vector<int> res(level);
while (label >= 1) {
res[level - 1] = label;
label = (1 << level) - 1 - label + (1 << (level - 1));
label /= 2;
--level;
}
return res;
}
};
``````

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1104

https://leetcode.com/problems/path-in-zigzag-labelled-binary-tree/

https://leetcode.com/problems/path-in-zigzag-labelled-binary-tree/discuss/323293/C%2B%2B-O(log-n)

https://leetcode.com/problems/path-in-zigzag-labelled-binary-tree/discuss/323312/Simple-solution-in-java-(Using-properties-of-complete-binary-tree)-(O-log-N)

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation