Path In Zigzag Labelled Binary Tree
Description
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(javascript)
// const TreeNode = function (val) {
// this.val = val
// this.parent = null
// this.left = null
// this.right = null
// }
// 构造树 O(n)
// const pathInZigZagTree = function (label) {
// const root = new TreeNode(1)
// let current = [root]
// let height = 1
// let targetNode = root
// while (2 ** (height) <= label) {
// const next = []
// if (height % 2 === 0) {
// for (let i = 2 ** height; i < 2 ** (height + 1); i++) {
// const node = new TreeNode(i)
// if (i === label) {
// targetNode = node
// }
// next.push(node)
// }
// } else {
// for (let i = (2 ** (height + 1)) - 1; i >= 2 ** height; i--) {
// const node = new TreeNode(i)
// if (i === label) {
// targetNode = node
// }
// next.push(node)
// }
// }
// for (let i = 0, j = 0; i <= current.length - 1; i++, j += 2) {
// current[i].left = next[j]
// current[i].right = next[j + 1]
// next[j].parent = current[i]
// next[j + 1].parent = current[i]
// }
// height += 1
// current = next
// }
// const result = []
// while (targetNode) {
// result.push(targetNode.val)
// targetNode = targetNode.parent
// }
// return result.reverse()
// }
// 观察规律 O(log(n))
const pathInZigZagTree = function (label) {
let height = 1
while ((2 ** height) - 1 < label) {
height += 1
}
const result = []
while (height > 0) {
result.push(label)
const max = (2 ** height) - 1
const min = 2 ** (height - 1)
label = Math.floor((max + min - label) / 2)
height -= 1
}
return result.reverse()
}