zoukankan      html  css  js  c++  java
  • 【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
  • 相关阅读:
    systemd 介绍
    Goland读取配置文件--viper包
    Goland日志记录
    进程查询端口占用
    Python zip() 函数
    Jenkins权限管理(角色权限)
    Django ORM查询总结
    如何查看windows计算机重启记录
    Django ORM迁移
    Django中文乱码解决
  • 原文地址:https://www.cnblogs.com/seyjs/p/11131279.html
Copyright © 2011-2022 走看看