您的位置:首页 > 编程语言 > Python开发

102. Binary Tree Level Order Traversal [easy] (Python)

2016-05-10 14:40 495 查看

题目链接

https://leetcode.com/problems/binary-tree-level-order-traversal/

题目原文

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]
]


题目翻译

给定一个二叉树,返回所有节点值的层序遍历结果。(从左到右,从上到下遍历)

比如,给出二叉树:{3,9,20,#,#,15,7},

3
/ \
9  20
/  \
15   7


它的层序遍历结果为:

[
[3],
[9,20],
[15,7]
]


思路方法

思路一

层序遍历的一般想法,做广度优先遍历(BFS)。遍历的同时,注意记录遍历结果要用满足题目要求的输出格式。

代码

# 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 levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
res = []
if root == None:
return res

q = [root]
while len(q) != 0:
res.append([node.val for node in q])
new_q = []
for node in q:
if node.left:
new_q.append(node.left)
if node.right:
new_q.append(node.right)
q = new_q

return res


思路二

用深度优先搜索(DFS),节点的深度与输出结果数组的下标相对应。注意在递归的时候要保存每次访问的节点值。

代码

# 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 levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
res = []
self.dfs(root, 0, res)
return res

def dfs(self, root, depth, res):
if root == None:
return res
if len(res) < depth+1:
res.append([])
res[depth].append(root.val)
self.dfs(root.left, depth+1, res)
self.dfs(root.right, depth+1, res)


PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!

转载请注明:/article/11857821.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: