[leetcode] 1104. Path In Zigzag Labelled Binary Tree

Description

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

分析

题目的意思是:找出给定结点在zigzag二叉树中到根结点的路径,这道题的难点在于公式推导,如果能够计算出来每个父节点的位置就好办了,递归求解父结点就可以了。怎么计算父结点的位置呢,可以首先把每一层最开始节点的编号求出来,即2^level,然后求出父结点到该层末数的个数:(label-corner)//2+1,由于父结点的编号跟当前节点的编号是相反的,所以最后编号:corner-1-th+1。可能也不是很明白,我这里写了一个可以debug的代码,可以debug感受一下过程。
比如n为14,那么其所在的层是3,2^3=8,第三层父结点到第四层相差的节点的个数:th为(14-8)//2+1=4,然后其所在的编号就是:corner-1-th+1=4.这样推算过来的。

代码

class Solution:
    def find_level(self,num):
        return math.floor(math.log(num,2))
    
    def find_parent(self,label):
        level=self.find_level(label)
        corner=2**level
        th=(label-corner)//2+1
        return corner-1-th+1
        
    def pathInZigZagTree(self, label: int) -> List[int]:
        res=[label]
        while(True):
            label=self.find_parent(label)
            if(label>=1):
                res.append(label)
            else:
                return res[::-1]

代码二

import math

class Solution:
    def __init__(self):
        super().__init__()
        self.corners=[]
        self.ths=[]
    def find_level(self,num):
        return math.floor(math.log(num,2))
    
    def find_parent(self,label):
        level=self.find_level(label)
        corner=2**level
        th=(label-corner)//2+1
        self.corners.append(corner)
        self.ths.append(th)
        return corner-1-th+1
        
    def pathInZigZagTree(self, label):
        res=[label]
        while(True):
            label=self.find_parent(label)
            if(label>=1):
                res.append(label)
            else:
                return res[::-1]
        

if __name__ == "__main__":
    solution=Solution()
    res=solution.pathInZigZagTree(14)
    print(res)
    print(solution.corners)
    print(solution.ths)
[1, 3, 4, 14]
[8, 4, 2, 1]
[4, 1, 1, 1]

参考文献

[1].Runtime: 24 ms, faster than 91.89% python. https://leetcode.com/problems/path-in-zigzag-labelled-binary-tree/discuss/629982/Runtime%3A-24-ms-faster-than-91.89-python

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值