Path In Zigzag Labelled Binary Tree Problem
Description
LeetCode Problem 1104.
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
Solution
Approach: Mirror, Then Halve
In a normal binary tree labelled row by row from left to right, the parent of label is simply label / 2. The zigzag order breaks that, but only by mirroring every other row, and we can undo the mirror.
Row r (counting from 1) holds the labels lo = 2^(r-1) up to hi = 2^r - 1. The node at the mirrored position in the same row has label lo + hi - label: the smallest and largest labels swap, the second and second-to-last swap, and so on.
Now take a node in row r. Its parent's row runs in the other direction. So mirror label first, which gives the label this node would have if its row ran the same way as the parent row, and then halve it: parent = (lo + hi - label) / 2. For example, 14 is in row 4 (8..15): (8 + 15 - 14) / 2 = 4, and 4 is indeed its parent.
Start from label, find its row from the number of bits of label, and keep stepping up until the root. The labels come out from the node to the root, so reverse them (or fill the array from the back).
Complexity: O(log label) time and space, one step per row.
class Solution:
def pathInZigZagTree(self, label: int) -> List[int]:
# Row r (1-based) holds the labels 2^(r-1) .. 2^r - 1.
row = label.bit_length()
path = []
while row >= 1:
path.append(label)
lo, hi = 1 << (row - 1), (1 << row) - 1
# lo + hi - label is the label at the same position if the row ran the other way;
# halving it gives the parent, because the parent's row runs the other way too.
label = (lo + hi - label) // 2
row -= 1
return path[::-1]