-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path102.二叉树的层序遍历.py
94 lines (89 loc) · 1.94 KB
/
102.二叉树的层序遍历.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#
# @lc app=leetcode.cn id=102 lang=python3
#
# [102] 二叉树的层序遍历
#
# https://leetcode.cn/problems/binary-tree-level-order-traversal/description/
#
# algorithms
# Medium (65.07%)
# Likes: 1450
# Dislikes: 0
# Total Accepted: 666.3K
# Total Submissions: 1M
# Testcase Example: '[3,9,20,null,null,15,7]'
#
# 给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。
#
#
#
# 示例 1:
#
#
# 输入:root = [3,9,20,null,null,15,7]
# 输出:[[3],[9,20],[15,7]]
#
#
# 示例 2:
#
#
# 输入:root = [1]
# 输出:[[1]]
#
#
# 示例 3:
#
#
# 输入:root = []
# 输出:[]
#
#
#
#
# 提示:
#
#
# 树中节点数目在范围 [0, 2000] 内
# -1000 <= Node.val <= 1000
#
#
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
# 1. 迭代 O(N) O(N)
if not root:
return []
res = []
queue = [root]
while queue:
size = len(queue)
tmp = []
for _ in range(size):
node = queue.pop(0)
tmp.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
res.append(tmp)
return res
# # 2. 递归 O(N) O(N)
# res = []
# def recur(node, depth):
# if not node:
# return
# if len(res) == depth:
# res.append([])
# res[depth].append(node.val)
# recur(node.left, depth+1)
# recur(node.right, depth+1)
# recur(root, 0)
# return res
# @lc code=end