[LeetCode] Path In Zigzag Labelled Binary Tree

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
vector<int> pathInZigZagTree(int label) {
vector<int> res;

while(label) {
res.push_back(label);
int level = log2(label), f = pow(2, level - 1), e = pow(2, level) - 1;;
bool right = level & 1;
if(right) {
int gap = e - label / 2;
label = f + gap;
} else {
int gap = label / 2 - f;
label = e - gap;
}
}

reverse(begin(res), end(res));
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/02/PS/LeetCode/path-in-zigzag-labelled-binary-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.