LeetCode 1104. Path In Zigzag Labelled Binary Tree解题报告

1104. Path In Zigzag Labelled Binary Tree

  1. Path In Zigzag Labelled Binary Tree python solution

题目描述

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.
在这里插入图片描述

解析

首先分析正常顺序二叉树的父节点寻找方法,如下图所示
在这里插入图片描述
例如节点9,其父结点为[9/2]=4,此题仅将排列变为Zigzag。变换后的排列方式见下图
在这里插入图片描述
分析二者之间的关系。分析zigzag的变换规则,原节点和该层最小节点的距离等于变换后新节点和该层最大节点的距离。分别用 x ′ x' x x x x代表zigzag中的节点和正常排序的原节点,则根据上述表达,可以得到公式:
x − m i n = m a x − x ′ x-min=max-x' xmin=maxx
因此, x = m a x + m i n − x ′ x=max+min-x' x=max+minx。所以就得到了原节点和现节点的变换公式。解题思路就是先求的zigzag节点对应的原节点,除于二取整得到其父节点。重复此步骤,直到根节点。

// An highlighted block
class Solution:
    def pathInZigZagTree(self, label: int) -> List[int]:
        height=int(math.log(label,2))
        record=[label]
        while(height):
            min=2**height
            max=2**(height+1)-1
            orign_node=min+max-label
            parent=int(orign_node/2)
            record.append(parent)
            label=parent
            height-=1
        return record[::-1]

Reference

https://leetcode.com/problems/path-in-zigzag-labelled-binary-tree/discuss/324011/Python-O(logn)-time-and-space-with-readable-code-and-step-by-step-explanation

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值