Skip to content

Commit 1b46375

Browse files
committed
二叉树相关 102题 二叉树的层序遍历
1 parent cf416c9 commit 1b46375

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
def levelOrder(root):
2+
"""
3+
:type root: TreeNode
4+
:rtype: List[List[int]]
5+
"""
6+
if root is None:
7+
return []
8+
queue = [root]
9+
ret = [[]]
10+
last_father = root
11+
while len(queue) != 0:
12+
op_node = queue[0]
13+
queue.remove(op_node)
14+
if last_father is not None and (last_father.left == op_node or last_father.right == op_node):
15+
local_ret = [op_node.val]
16+
ret.append(local_ret)
17+
last_father = None
18+
else:
19+
ret[-1].append(op_node.val)
20+
if op_node.left is not None:
21+
queue.append(op_node.left)
22+
if last_father is None:
23+
last_father = op_node
24+
if op_node.right is not None:
25+
queue.append(op_node.right)
26+
if last_father is None:
27+
last_father = op_node
28+
29+
return ret

0 commit comments

Comments
 (0)