题目如下:

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

最新文章

  1. 微信网页开发之获取用户unionID的两种方法--基于微信的多点登录用户识别
  2. VC中对文件的读写
  3. Git常用
  4. javascript学习笔记2-typeof、Number类型、Boolean()
  5. address元素
  6. 关于Android开发手机连接不上电脑问题解决方案
  7. worker启动executor源码分析-executor.clj
  8. [转]T4模版引擎之生成数据库实体类
  9. ubuntu无法进入和引导顺序问题解决
  10. hdu5045:带权二分图匹配
  11. English - refer to...和refer to...as
  12. spring配置文件详解【总结】
  13. ABP+AdminLTE+Bootstrap Table权限管理系统第九节--AdminLTE模板页搭建
  14. 后台工作者HangFire与ABP框架Abp.Hangfire及扩展
  15. 深夜学算法之SkipList:让链表飞
  16. 解决Idea无法提示代码、不检查语法的方法
  17. JS 中 原生方法 (一) --- 字符串
  18. html 标签学习(续)
  19. Apache 源码安装
  20. C Programming vs. Java Programming

热门文章

  1. 阶段3 1.Mybatis_11.Mybatis的缓存_4 mybatis一对多实现延迟加载
  2. Eclipse设置保存时自动格式化代码
  3. Python中的Django框架中prefetch_related()函数对数据库查询的优化
  4. CSS3——边框 圆角 背景 渐变 文本效果
  5. Struts2框架学习笔记1
  6. 【Linux开发】./configure,make,make install的作用
  7. 【css】子元素浮动到了父元素外,父元素没有随子元素自适应高度,如何解决?
  8. IntelliJ IDEA 快捷键终极大全
  9. 转 appium grid分布式环境搭建
  10. 锋利的jQuery 要点归纳(一) jQuery选择器