[LeetCode]102 二叉树的层次遍历

题目描述

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

例如:
给定二叉树:[3,9,20,null,null,15,7],

  3
 / \
9  20
  /  \
 15   7

返回其层次遍历结果:

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

代码

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
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution:
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if root == None:
return []
stack = [root]
res = []
while stack != []:
x = []
for item in stack:
x.append(item.val)
res.append(x)
tmp = []
for item in stack:
if item.left != None:
tmp.append(item.left)
if item.right != None:
tmp.append(item.right)
stack = tmp
return res