Python 中之字形标记二叉树中的路径
假设在一个无限二叉树中,每个节点都有两个子节点,节点按行顺序标记。现在在奇数行(第一、第三、第五……)中,标记是从左到右,在偶数行(第二、第四、第六……)中,标记是从右到左。所以树将像 −

因此,我们给出了这棵树中一个节点的标签,我们必须找到从树的根到具有该标签的节点的路径中的标签。因此,如果输入为 label = 14,则输出将为 [1,3,4,14]
为了解决这个问题,我们将遵循以下步骤 −
定义两个数组 tree 和 res,将 0 和 1 插入树数组,设置 odd := 1 和 current := 1 和 two := 2
如果 label = 1,则返回一个包含单个元素 1 的列表。
创建一个无限循环 −
如果 odd 非零,则
max_val := current + two
temp := max_val
while temp > current
将 temp 插入树中
如果 temp = label,则退出循环
将 temp 减少 1
如果树的最后一个元素是 label,则退出循环
current := max_val
否则
temp := two
当 temp 不为零时
temp := 1,将 current 增加 1,然后将 current 增加到树中
如果 current = label,则退出循环
如果树的最后一个元素是标签,则退出循环
temp := temp * 2
如果 odd 不为零,odd := false,否则为 true
index := 树的长度 – 1
当 index 不为 0 时
将 tree[index] 插入 res 数组
index := index / 2
res := res 的反向列表
返回 res
示例 (Python)
让我们看下面的实现,以便更好地理解 −
class Solution(object): def pathInZigZagTree(self, label): tree = [] res = [] tree.append(0) tree.append(1) odd = 1 current = 1 two = 2 if label == 1: return [1] while True: if odd: max_val = current + two temp = max_val while temp>current: tree.append(temp) if temp == label: break temp-=1 if tree[-1]== label: break current = max_val else: temp = two while temp: temp-=1 current+=1 tree.append(current) if current == label: break if tree[-1]== label: break two*=2 odd = not odd index = len(tree)-1 while index: res.append(tree[index]) index//=2 res=res[::-1] return res ob = Solution() print(ob.pathInZigZagTree(14))
输入
14
输出
[1,3,4,14]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

