【LeetCode-103】Binary Tree Zigzag Level Order Traversal
2016-04-17 21:05
537 查看
这道题只需在102的基础上稍微变化下就行,很简单了,fighting
class Solution(object):
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
# 最终结果
res = []
# 存放每一层结果
levelRes = []
if root == None:
return res
# 当前一层的节点
current = []
# 下一层的节点
next = []
# 根节点加入
current.append(root)
# 标记是正向还是反向来
flag = True
while len(current) > 0:
node = current.pop()
if flag:
# (正向,则先添加左节点,再添加右节点)
if node.left != None:
next.append(node.left)
if node.right != None:
next.append(node.right)
else :
# (反向。先添加右节点,再添加左节点)
if node.right != None:
next.append(node.right)
if node.left != None:
next.append(node.left)
# 加入访问节点的值
levelRes.append(node.val)
if len(current) == 0:
current = next
next = []
res.append(levelRes)
levelRes = []
# 将flag取反
flag = not flag
return res
class Solution(object):
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
# 最终结果
res = []
# 存放每一层结果
levelRes = []
if root == None:
return res
# 当前一层的节点
current = []
# 下一层的节点
next = []
# 根节点加入
current.append(root)
# 标记是正向还是反向来
flag = True
while len(current) > 0:
node = current.pop()
if flag:
# (正向,则先添加左节点,再添加右节点)
if node.left != None:
next.append(node.left)
if node.right != None:
next.append(node.right)
else :
# (反向。先添加右节点,再添加左节点)
if node.right != None:
next.append(node.right)
if node.left != None:
next.append(node.left)
# 加入访问节点的值
levelRes.append(node.val)
if len(current) == 0:
current = next
next = []
res.append(levelRes)
levelRes = []
# 将flag取反
flag = not flag
return res
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法