-
Notifications
You must be signed in to change notification settings - Fork 7
/
printManyLines.py
46 lines (39 loc) · 1.03 KB
/
printManyLines.py
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# -*- coding:utf-8 -*-
"""
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
1
/ \
2 3
/ \ \
4 5 7
输出:[[1], [2, 3], [4, 5, 7]]
"""
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def Print(self, pRoot):
"""
提示:
把每一层节点都存到队列(列表)中
"""
# write code here
if pRoot is None:
return []
queue = [pRoot]
LValue = []
while queue:
thisLayer = queue[:]
del queue[:]
tValue = []
for node in thisLayer:
tValue.append(node.val)
LValue.append(tValue)
for node in thisLayer:
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return LValue