class Solution:
def pathInZigZagTree(self, label: int) -> List[int]:
depth = 0
for i in range(1,10000):
if label>=2**(i-1) and label<2**(i):
depth = i
break
res = [label,]
if depth==1:
return res
while depth>2:
if depth%2==0:
right = math.pow(2,depth-1)
index = (label-right)//2
temp = right-index-1
else:
left = math.pow(2,depth-1)
index = (label-left)//2
temp = left-index-1
depth-=1
label = temp
res.append(int(temp))
res.append(1)
return res[::-1]
说好的每日一题又来了,今天是一个找规律的题,先自己行理解一波题目,目前有一个无限大小的二叉树,而且是满二叉树。然后建树的规则是从1开始,奇数行是从做到右,偶数行是从右到左,每一层的范围都是确定的,对于第n层来说,最小值是2**n-1,最大值是不超过2**n。然后我们对奇数行和偶数行分别做处理。题目的最终结果是需要找出每个节点的父节点。
- 奇数行
- 先确定偶数行的最小值
- 然后用当前的lable值减去最小值,在整除2,最终得到当前节点的父节点在上一次的第几个位置
- 然后用上一层的起始值和最终的位置就能判断当前label的父节点了
- 偶数行
- 同理