当前位置:网站首页>【二叉树-中等】1104. 二叉树寻路
【二叉树-中等】1104. 二叉树寻路
2022-08-10 01:52:00 【菜菜2022】
【题目】
【代码】
class Solution:
def pathInZigZagTree(self, label: int) -> List[int]:
parents=[]
levels=[]
def levelVisit(label):
nonlocal levels
for level_id in range(1,1001):
level=[pow(2,level_id)+i for i in range(pow(2,level_id))]
levels.append(level)
if label in level:
break
levels=levels[::-1]
# print(levels)
for idx,level in enumerate(levels):
parents.append(label)
if label not in levels[idx]:
break
cur_pos=levels[idx].index(label)//2
# print("idx:",idx," cur_pos:",cur_pos)
if idx!=len(levels)-1:
label=levels[idx+1][len(levels[idx+1])-1-cur_pos]
if label==1:
return [1]
levelVisit(label)
parents.append(1)
# print(parents)
return parents[::-1]
【方法2】来自麦麦麦麦子。的题解

class Solution:
def pathInZigZagTree(self, label: int) -> List[int]:
res = []
while label != 1:
res.append(label)
label >>= 1
label = label ^(1 << (label.bit_length() - 1)) - 1
return [1]+res[::-1]
边栏推荐
猜你喜欢
随机推荐
微透镜阵列后光传播的研究
OOD论文:Revisit Overconfidence for OOD Detection
【wpf】自定义事件总结(Action, EventHandler)
781. 森林中的兔子
彩色袜子题
OptiFDTD应用:纳米盘型谐振腔等离子体波导滤波器
type-C 边充电边听歌(OTG) PD芯片方案,LDR6028 PD充电加OTG方案
桌面云组件介绍与安装
hint: Updates were rejected because the tip of your current branch is behind hint: its remote counte
【内存管理概述 Objective-C语言】
.Net面试经验总结
OpenCV图像处理学习一,加载显示修改保存图像相关函数
Summary of Web Performance Testing Models
Nacos源码分析专题(五)-Nacos小结
Unity image使用长图后 图片很糊
Experimental support for decorators may change in future releases.Set the "experimentalDecorators" option in "tsconfig" or "jsconfig" to remove this warning
阿里云OSS文件上传
【wpf】拖拽的简单实现
翻译工具-翻译工具下载批量自动一键翻译免费
hint: Updates were rejected because the tip of your current branch is behind hint: its remote counte








