leetcode1104

 1 import math
 2 class Solution:
 3     def findParent(self,label,pardepth):
 4         psum = 2**(pardepth-1) + 2**(pardepth) - 1
 5         label = label // 2
 6         dlabel = psum - label
 7         return dlabel 
 8 
 9     def pathInZigZagTree(self, label: int) -> 'List[int]':
10         depth = math.ceil(math.log(label,2))
11         if label == 2 ** depth:
12             depth += 1
13         #print(depth)
14         res = [label]
15         while depth > 1:
16             label = self.findParent(label,depth-1)
17             res.insert(0,label)
18             depth -= 1 
19         return res

本题是全排列树的变形,相邻高度的层,逆序排列。

因此先判断目标label节点的高度,然后计算其父节点,并将父节点插入结果列表。

原文地址:https://www.cnblogs.com/asenyang/p/11109426.html