-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path107.二叉树的层次遍历-ii.py
67 lines (58 loc) · 1.34 KB
/
107.二叉树的层次遍历-ii.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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#
# @lc app=leetcode.cn id=107 lang=python3
#
# [107] 二叉树的层次遍历 II
#
# https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii/description/
#
# algorithms
# Easy (63.30%)
# Likes: 188
# Dislikes: 0
# Total Accepted: 41.4K
# Total Submissions: 64.4K
# Testcase Example: '[3,9,20,null,null,15,7]'
#
# 给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
#
# 例如:
# 给定二叉树 [3,9,20,null,null,15,7],
#
# 3
# / \
# 9 20
# / \
# 15 7
#
#
# 返回其自底向上的层次遍历为:
#
# [
# [15,7],
# [9,20],
# [3]
# ]
#
#
#
from typing import List
# @lc code=start
# 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: TreeNode) -> List[List[int]]:
"""
1. 层序遍历,然后逆转 或 deque.appendleft
"""
from collections import deque
res = deque()
lvl = [root]
while any(lvl):
res.appendleft([node.val for node in lvl])
lvl = [child for node in lvl for child in [node.left, node.right] if child]
return list(res)
# @lc code=end