#1104
Medium Algorithms Path in zigzag labelled binary tree
Math Tree Binary Tree
75.8% acceptance
Feb 25, 2026
1546
329
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.
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn path_in_zig_zag_tree(label: i32) -> Vec<i32> {
let mut result = Vec::new();
let mut node = label;
while node >= 1 {
result.push(node);
let level = (node as f64).log2() as i32;
let level_start = 1i32 << level;
let level_end = (1i32 << (level + 1)) - 1;
let mirror = level_start + level_end - node;
node = mirror / 2;
}
result.reverse();
result
}
}