Skip to content

1104. 二叉树寻路

Published: at 23:30
1
2 3
4 5 6 7

如果是正序的话,上一个节点就是 label / 2;但像是这种倒过来的情况的话,就需要 reverse 一下。

impl Solution {
pub fn path_in_zig_zag_tree(label: i32) -> Vec<i32> {
let layer = label.ilog2() as usize;
let mut label = label;
let mut should_reverse = false;
let mut result = vec![0; layer + 1];
for i in (0..=layer).rev() {
result[i] = if should_reverse {
// 2^(i+1)-1 .. x .. y .. 2^i
// y - 2^i = 2^i * 2 - 1 - x
// y = 2^i * 3 - 1 - x
2_i32.pow(i as u32) * 3 - 1 - label
} else {
label
};
should_reverse = !should_reverse;
label = label / 2;
}
result
}
}

Previous Post
1103. 分糖果II
Next Post
70. 爬楼梯