1104. Path In Zigzag Labelled Binary Tree
- 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'
x−min=max−x′
因此,
x
=
m
a
x
+
m
i
n
−
x
′
x=max+min-x'
x=max+min−x′。所以就得到了原节点和现节点的变换公式。解题思路就是先求的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