-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2178_levelOrder.py
35 lines (34 loc) · 1.09 KB
/
2178_levelOrder.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
# 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[int]
"""
if root is None: return []
queue = list()
result = []
queue.append(root)
height = 1 # 记录当前层
while (len(queue) != 0):
# 每次把queue里所有元素的孩子都加入 并把父节点全都删除
cur_level = queue
queue = [] # 父节点全部出队
# 子节点全部入队
for father in cur_level:
if father.left is not None:
queue.append(father.left)
if father.right is not None:
queue.append(father.right)
tmp = []
for item in cur_level:
tmp.append(item.val)
if height % 2 == 0: tmp.reverse()
height += 1
result.append(tmp)
return result