【Leetcode】【python】Binary Tree Level Order Traversal II

题目大意

层序输出二叉树,这次是从最下层输出到根节点

解题思路

只要在Binary Tree Level Order Traversal的基础上加一行反转

代码

DFS代码请看上面一题,都只要加一行。

BFS

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
# 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 levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
tree = []
if not root:
return tree
curr_level = [root]
# print(type(root), type(curr_level)) # (<class 'precompiled.treenode.TreeNode'>, <type 'list'>)
# print(curr_level) # 作为list,却并不能遍历整个树
while curr_level:
level_list = []
next_level = []
for temp in curr_level:
level_list.append(temp.val)
if temp.left:
next_level.append(temp.left)
if temp.right:
next_level.append(temp.right)
tree.append(level_list)
curr_level = next_level
tree.reverse()
return tree

总结

  1. tree.reverse()反转