[LeetCode]107 二叉树的层次遍历II

题目描述

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

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

  3
 / \
9  20
  /  \
 15   7

返回其自底向上的层次遍历为:

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

代码

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

class Solution:
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if root == None:
return []
stacks = []
new_stack = [root]
stacks.append(new_stack)

while new_stack != []:
new_stack_2 = []
for i in new_stack:
if i.left is None and i.right is None:
continue
if i.left is not None:
new_stack_2.append(i.left)
if i.right is not None:
new_stack_2.append(i.right)
new_stack = new_stack_2
stacks.append(new_stack)
stacks.pop()

results = []
for stack in stacks:
result = []
for _ in stack:
result.append(_.val)
results.append(result)
return results[::-1]