Leetcode 102.二叉树的层次遍历

102.二叉树的层次遍历

题目

给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
例如:
给定二叉树: [3,9,20,null,null,15,7],

3
/ \
9 20
/ \
15 7
返回其层次遍历结果:

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

方法

方法1:宽度优先遍历

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# 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]]
"""

if not root:
return []

queue=collections.deque([(root)])
ans=[]
while queue:
level=[]
for i in range(len(queue)):
node=queue.popleft()
if node:
level.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
ans.append(level)
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# 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]]
"""

if not root:
return []

queue=collections.deque([(root)])
ans=[]
while queue:
level=[]
q=collections.deque()
while queue:
node=queue.popleft()
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
level.append(node.val)
ans.append(level)
queue=q
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution(object):
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if root == None:
return []
tmp = [root]
res = []
while tmp:
value = []
l = len(tmp)
i = 0
while i < l:
t = tmp.pop(0)
value.append(t.val)
if t.left:
tmp.append(t.left)
if t.right:
tmp.append(t.right)
i += 1
res.append(value)
return res