Leetcode 1104. Binary Tree Pathfinding

Leetcode 1104. Binary Tree Pathfinding

topic

在一棵无限的二叉树上,每个节点都有两个子节点,树中的节点 逐行 依次按 “之” 字形进行标记。

如下图所示,在奇数行(即,第一行、第三行、第五行……)中,按从左到右的顺序进行标记;

而偶数行(即,第二行、第四行、第六行……)中,按从右到左的顺序进行标记。

给你树上某一个节点的标号 label,请你返回从根节点到该标号为 label 节点的路径,该路径是由途经的节点标号所组成的。

Insert picture description here

Example 1:

输入:label = 14
输出:[1,3,4,14]

Example 2:

输入:label = 26
输出:[1,2,6,10,26]

Ideas

  • First of all, this question does not need to be considered from the perspective of the tree, because the range given is 10^6
  • The tree of this topic must be a complete binary tree. If it is a normal tree, parent node label = child node label // 2
  • The tree in this topic is a zigzag traversal, so we carefully observe the law and find that the parent node label = (the maximum value of the child node's layer + the minimum value of the layer-the child node label) // 2
  • So we can first find which layer the current label is
  • Then traverse down layer by layer

Code

class Solution:
    def pathInZigZagTree(self, label):
        floor = 1

        while 2 ** floor - 1 < label:
            floor += 1

        res = []

        for i in range(floor, 0, -1):
            res.append(label)
            label = (2 ** i - 1 + 2 ** (i - 1) - label) // 2

        return res[-1::-1]

Guess you like

Origin blog.csdn.net/weixin_43891775/article/details/113032006