【leetcode】1104. Path In Zigzag Labelled Binary Tree

题目如下:

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]

 

Constraints:

  • 1 <= label <= 10^6

解题思路:先把正常的路径(即不是蛇形排列的数)求出来,接下来自底向顶遍历,偶数行的值需要交换,交换的逻辑也很简单,求出该层最左边和最右边的节点的number,记为low和一个high,那么对于number为inx的节点,其交换后的number就是: (low + high) - inx。

代码如下:

class Solution(object):
    def pathInZigZagTree(self, label):
        """
        :type label: int
        :rtype: List[int]
        """
        res = []
        level = 0
        while label != 0:
            res.insert(0,label)
            label = label/2
            level += 1

        swap = False
        while level > 0:
            if swap:
                low = 2**(level-1)
                high = (low * 2 - 1)
                res[level-1] = (low + high) - res[level-1]
            swap = not swap
            level -= 1
        return res

 

转载于:https://www.cnblogs.com/seyjs/p/11131279.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值