您的位置:首页 > 其它

二叉树的锯齿形层次遍历

2016-04-17 10:42 246 查看
题目描述:给出一棵二叉树,返回其节点值的锯齿形层次遍历(先从左往右,下一层再从右往左,层与层之间交替进行)

样例:



如果之前的二叉树的层次遍历(详见我的博文:点击打开链接)你已经完全搞懂的话,这道题其实基本对你是没有什么意义的,他还是层次遍历,只不过相邻每两层之间输出的顺序相反。

那这个是很容易解决的,设置一个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的语法规则,注意一下就行
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  二叉树 遍历