[LeetCode]题解(python):103-Binary Tree Zigzag Level Order Traversal
2016-03-07 18:26
579 查看
[b]题目来源:[/b]
https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
[b]题意分析:[/b]
Z字宽度遍历树。
[b]题目思路:[/b]
这题可以用比较取巧的方法。首先获得宽度遍历的结果,然后将第二层的翻转就可以了。
[b]代码(python):[/b]
[b] [/b]
View Code
https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
[b]题意分析:[/b]
Z字宽度遍历树。
[b]题目思路:[/b]
这题可以用比较取巧的方法。首先获得宽度遍历的结果,然后将第二层的翻转就可以了。
[b]代码(python):[/b]
[b] [/b]
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def zigzagLevelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ ans = [] def bfs(root,level): if root != None: if len(ans) < level + 1: ans.append([]) ans[level].append(root.val) bfs(root.left,level + 1) bfs(root.right,level + 1) bfs(root,0) i = 1 while i < len(ans): ans[i].reverse() i += 2 return ans
View Code
相关文章推荐
- C\C#\Java\Python 基本数据类型比较
- [LeetCode]题解(python):102- Binary Tree Level Order Traversal
- windows系统下Python环境的搭建
- [LeetCode]题解(python):101-Symmetric Tree
- 【python】编程语言入门经典100例--24
- Numpy使用1
- Python对象赋值、浅拷贝和深拷贝
- python系列之 - 面向对象(二)
- [LeetCode]题解(python):100-Same Tree
- Python Basics
- python2x的str/unicode转换以及python3x中的str/bytes转换
- python Queue学习
- [LeetCode]题解(python):099-Recover Binary Search Tree
- github/python/ show me the code 25题(一)
- Python任务调度模块 – APScheduler
- python解析json数据
- 关于Python的super用法研究
- VPython—旋转坐标系
- [LeetCode]题解(python):098- Validate Binary Search Tree
- python入门(二)