The first thing I thought of was to construct a binary tree, and then use the symmetric relationship of each layer to find the parent node
var pathInZigZagTree = function(label) {
let stack = []
for (let i = 1; i <= label; i++) {
let level = Math.floor(Math.log(i) / Math.log(2))
if (!stack[level]) {
stack[level] = []
}
if (level % 2 === 0) {
stack[level].push(i)
} else {
stack[level].unshift(i)
}
}
var level = Math.floor(Math.log(label) / Math.log(2))
let ans = []
while (level) {
ans.push(label)
level--
label = Math.floor(label / 2)
let index = stack[level].length - 1 - stack[level].indexOf(label)
label = stack[level][index]
}
ans.push(1)
return ans.reverse()
}Sorry, timeout.
Inspired by the answer, since it is symmetrical, the sum of the symmetrical numbers is the same when the number of layers is the same.
The first term of the first layer is 2^n, and the last term is 2^(n + 1) - 1. The symmetric number 2^n + 2^(n + 1) - 1 - x
Right now
( 1 << row ) + ( 1 << (row + 1) ) - 1 - label;
The last digit of the search must be 1, which can be used as the end of the while statement.
var pathInZigZagTree = function(label) {
let row = Math.floor(Math.log(label) / Math.log(2))
let ans = []
while (label !== 1) {
ans.unshift(label)
row--
label = getReverse(Math.floor(label / 2), row)
}
ans.unshift(1)
return ans
}
const getReverse = (label, row) => {
return (1 << row) + (1 << (row + 1)) - 1 - label
}The first thing I thought of was to construct a binary tree, and then use the symmetric relationship of each layer to find the parent node
var pathInZigZagTree = function(label) {
let stack = []
for (let i = 1; i <= label; i++) {
let level = Math.floor(Math.log(i) / Math.log(2))
if (!stack[level]) {
stack[level] = []
}
if (level % 2 === 0) {
stack[level].push(i)
} else {
stack[level].unshift(i)
}
}
var level = Math.floor(Math.log(label) / Math.log(2))
let ans = []
while (level) {
ans.push(label)
level--
label = Math.floor(label / 2)
let index = stack[level].length - 1 - stack[level].indexOf(label)
label = stack[level][index]
}
ans.push(1)
return ans.reverse()
};Sorry, timeout.
Inspired by the answer, since it is symmetrical, the sum of the symmetrical numbers is the same when the number of layers is the same.
The first term of the first layer is 2^n, and the last term is 2^(n + 1) - 1. The symmetric number 2^n + 2^(n + 1) - 1 - x
Right now
( 1 << row ) + ( 1 << (row + 1) ) - 1 - label;
The last digit of the search must be 1, which can be used as the end of the while statement.
var pathInZigZagTree = function(label) {
let row = Math.floor(Math.log(label) / Math.log(2))
let ans = []
while (label !== 1) {
ans.unshift(label)
row--
label = getReverse(Math.floor(label / 2), row)
}
ans.unshift(1)
return ans
};
const getReverse = (label, row) => {
return (1 << row) + (1 << (row + 1)) - 1 - label;
};