1 题目
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]
2 尝试解
2.1 分析
一个无限大的完全二叉树,其值按Z字型从1依序递增1。给定一个值,问从根节点到该值所在节点的路径。
考虑同样的二叉树,但是值按照每层从左向右的顺序依序递增1。在此二叉树中,发现任意一个值为N的节点,其父节点的值为N/2。所以只需要重复取半,即可得到从该节点到根节点的路径。如给定14,路径为{14,7,3,1}。
1 1
/ \ / \
3 2 2 3
/ \ / \ / \ / \
4 5 6 7 4 5 6 7
现在考虑两棵二叉树之间的相互转化,给定值label及其所在的层数height(可由label求出),label'表示对应节点在另一棵二叉树中的值,有
height%2 == 0 label = label'
height%2 == 1 label+label' = 2^height + 2^(height-1) - 1
只需要对路径中的每个元素采用上述转化规则,即将一个路径转化为另一个对应路径。
2.2 代码
class Solution {
public:
int transform(int label, int height){
if(height % 2 == 1) return label;
else return (1 << height) - label - 1 + (1 << (height-1));
}
vector<int> pathInZigZagTree(int label) {
int height = 1;
vector<int> result;
while(label >= (1 << height)){
height += 1;
}
label = transform(label,height);
while(height > 0){
result.push_back(transform(label,height));
label /= 2;
height--;
}
reverse(result.begin(),result.end());
return result;
}
};