题目
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
题意
给定一个label,根据label生成二叉树,如上图所示,这颗二叉树是一颗满二叉树,深度是label所在深度,其中从上到下是节点值依次递增,偶数行节点逆序排列,奇数行节点顺序排列,要在这颗树种找到从根节点到label所在节点路径上的值。
代码
这个题的解法应该有很多,我的想法是想按每行节点都是顺序排列来找出这一条路径,然后找出路径上偶数行节点的对称节点,替换路径中该节点的值,具体代码如下:
import java.util.ArrayList;
import java.util.List;
class Solution {
public List<Integer> pathInZigZagTree(int label) {
List<Integer> result = new ArrayList<>();
int high = 0;
int index = label;
// 在全部为顺序排列的情况下找出路径
while (index > 0){
result.add(0,index);
if (index % 2 != 0){
index = (index - 1) / 2;
}else {
index = index / 2;
}
}
// 为路径中奇数行的节点找对称节点
// 当result节点数量(也就是树的深度)是偶数时,则reuslt偶数索引需要在树种找对称节点
if (result.size() % 2 == 0) {
for (int i = 2; i < result.size() - 1; i+=2) {
if (i % 2 == 0){
int rowMax = (int) Math.pow(2,i + 1) - 1;
int rowMin = rowMax - (int)Math.pow(2,i) + 1;
result.set(i,rowMin + (rowMax - result.get(i)));
}
}
// 当result节点数量(也就是树的深度)是奇数时,则reuslt奇数索引需要在树种找对称节点
}else {
for (int i = 1; i < result.size() - 1; i+=2) {
if (i % 2 != 0){
int rowMax = (int) Math.pow(2,i + 1) - 1; // 当前行最大值
int rowMin = rowMax - (int)Math.pow(2,i) + 1; // 当前行最小值
result.set(i,rowMin + (rowMax - result.get(i))); // 节点和最大值的距离就是对称节点和最小值的距离,所以此处找出对称节点值
}
}
}
return result;
}
}