• 【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
  • 相关阅读:
    (转)一台服务器安装两个tomcat6 服务的解决方案
    目标的改变
    常用但易忘的sql语句及java程序
    数据可视化工具 Gephi
    R中library和require的区别
    python BeautifulSoup解决中文乱码问题
    【转载】MySQL全文检索笔记
    poj 1011
    Nest,很酷的东西
    H.264开源解码器评测
  • 原文地址:https://www.cnblogs.com/seyjs/p/11131279.html
Copyright © 2020-2023  润新知