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
  • 相关阅读:
    bzoj 2038 [2009国家集训队]小Z的袜子(hose)
    搭配飞行员
    codevs 1022 覆盖
    Tyvj-1338 QQ农场
    bzoj 3894 文理分科
    bzoj 1877 [SDOI2009]晨跑
    poj 3304 判断是否存在一条直线与所有线段相交
    poj 2318 向量的叉积二分查找
    poj 3608 凸包间的最小距离
    LA 4728 旋转卡壳算法求凸包的最大直径
  • 原文地址:https://www.cnblogs.com/seyjs/p/11131279.html
Copyright © 2011-2022 走看看