二叉树的锯齿形层次遍历
2016-04-17 10:42
246 查看
题目描述:给出一棵二叉树,返回其节点值的锯齿形层次遍历(先从左往右,下一层再从右往左,层与层之间交替进行)
样例:
如果之前的二叉树的层次遍历(详见我的博文:点击打开链接)你已经完全搞懂的话,这道题其实基本对你是没有什么意义的,他还是层次遍历,只不过相邻每两层之间输出的顺序相反。
那这个是很容易解决的,设置一个bool型的变量,每次判断是该从左往右,还是从右往在即可。然后每遍历一层,对这个bool型变量取反。
太简单了,直接上代码:
样例:
如果之前的二叉树的层次遍历(详见我的博文:点击打开链接)你已经完全搞懂的话,这道题其实基本对你是没有什么意义的,他还是层次遍历,只不过相邻每两层之间输出的顺序相反。
那这个是很容易解决的,设置一个bool型的变量,每次判断是该从左往右,还是从右往在即可。然后每遍历一层,对这个bool型变量取反。
太简单了,直接上代码:
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: The root of binary tree. @return: A list of list of integer include the zig zag level order traversal of its nodes' values """ def zigzagLevelOrder(self, root): result = [] if root is None: return result cur_list = [root] level = [] cur_count, next_count = 1, 0 left_to_right = False while len(cur_list) != 0: while cur_count != 0: temp = cur_list.pop(0) level.append(temp.val) cur_count = cur_count - 1 if temp.left: cur_list.append(temp.left) next_count = next_count + 1 if temp.right: cur_list.append(temp.right) next_count = next_count + 1 left_to_right = not left_to_right if left_to_right: result.append(level) else: level.reverse() result.append(level) cur_count = next_count next_count = 0 level = [] return result # write your code here需要注意的一点是39行,level.reverse()是对列表level做了翻转,它并没有返回值,所以不能写成level = level.reverse().这是Python的语法规则,注意一下就行
相关文章推荐
- AVL树-自平衡二叉查找树(Java实现)
- 文件遍历排序函数
- Lua 学习笔记之C API 遍历 Table实现代码
- C#遍历文件夹后上传文件夹中所有文件错误案例分析
- C#中遍历Hashtable的4种方法
- Erlang中遍历取出某个位置的最大值代码
- C++实现图的邻接矩阵存储和广度、深度优先遍历实例分析
- C++实现图的邻接表存储和广度优先遍历实例分析
- C语言二叉树的非递归遍历实例分析
- 使用C语言构建基本的二叉树数据结构
- 一波二叉树遍历问题的C++解答实例分享
- 举例讲解C语言程序中对二叉树数据结构的各种遍历方式
- C++非递归队列实现二叉树的广度优先遍历
- php遍历目录方法小结
- 一个目录遍历函数
- php遍历删除整个目录及文件的方法
- PHP遍历文件夹与文件类及处理类用法实例
- PHP遍历XML文档所有节点的方法
- 平衡二叉树
- 二叉树