[LeetCode] Binary Tree Level Order Traversal
来源:互联网 发布:网络教育课程 编辑:程序博客网 时间:2024/05/29 18:01
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree {3,9,20,#,#,15,7}
,
3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7]]
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1 / \ 2 3 / 4 \ 5The above binary tree is serialized as
"{1,2,3,#,#,4,#,#,5}"
.元素在那一层,这里借鉴了别人的思想:设置两个标记量分别标记parent数和child数,再说一次,要得到按层遍历的序列不难,难的是怎么确定什么时候是分层,开始的
时候queue只有root一个元素,此时parentIndex = 1, childIndex = 0,由于它的left和right都为飞空,所以root.left 和 root.right 分别入队列,
childIndex 递增两次,即childIndex += 2。。。算了,我也说不清,还是上代码吧:
class TreeNode:def __init__(self, x):self.val = xself.left = Noneself.right = Noneclass Solution:# @param root, a tree node# @param sum, an integer# @return a booleandef levelOrder(self, root):if None == root:return []queue = [root]ret = []tmp = []parentIndex = 1childIndex = 0while len(queue) > 0:leaf = queue[0]tmp.append(leaf.val)del queue[0]if None != leaf.left:queue.append(leaf.left)childIndex += 1if None != leaf.right:queue.append(leaf.right)childIndex += 1parentIndex -= 1if 0 == parentIndex:ret.append(tmp)tmp = []parentIndex = childIndexchildIndex = 0return ret
0 0
- LeetCode[Tree]: Binary Tree Level Order Traversal
- *(leetcode) Binary Tree Level Order Traversal (tree)
- [leetcode][tree] Binary Tree Level Order Traversal
- LeetCode: Binary Tree Level Order Traversal
- LeetCode: Binary Tree Zigzag Level Order Traversal
- LeetCode: Binary Tree Level Order Traversal II
- [LeetCode]Binary Tree Level Order Traversal
- [LeetCode]Binary Tree Level Order Traversal II
- [LeetCode]Binary Tree Zigzag Level Order Traversal
- LeetCode Binary Tree Level Order Traversal
- LeetCode Binary Tree Level Order Traversal II
- LeetCode Binary Tree Zigzag Level Order Traversal
- [Leetcode] Binary Tree Level Order Traversal
- [Leetcode] Binary Tree Level Order Traversal II
- [Leetcode] Binary Tree Zigzag Level Order Traversal
- Leetcode: Binary Tree Zigzag Level Order Traversal
- LeetCode Binary Tree Level Order Traversal
- LeetCode Binary Tree Level Order Traversal II
- JavaScript浏览器访问/上传本地文件
- 本人常用资源整理(ing...)
- css学习笔记——CSS 属性 选择器
- Windows Azure(世纪互联版)- 几个注意事项
- 黑马程序员_IO流学习第一天
- [LeetCode] Binary Tree Level Order Traversal
- 有关epoll的EPOLLOUT
- const关键字
- string 将指定的字符或字符串全部替换成特定的字符或字符串
- IOS7 label 宽度高度自适应
- Linux之旅(I)——Ubuntu 12.04/14.04 LTS 安装
- STM8使用----STVD(COSMIC)定义变量指定其类型和位定义
- 解析:求最大公约数的“辗转相除法原理”
- Linux环境进程间通信(五):共享内存(上)