102. 二叉树的层序遍历
xxxixxxx

102. 二叉树的层序遍历

  • 时间复杂度
    O(n) 每个节点访问一次
  • 空间复杂度
    O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
func levelOrder(_ root: TreeNode?) -> [[Int]] {
guard let root = root else { return [] }
var treeList: [TreeNode] = [root]
var ans: [[Int]] = []

while !treeList.isEmpty {
var valList: [Int] = []
var tempList: [TreeNode] = []
for tree in treeList {
valList.append(tree.val)
if tree.left != nil {
tempList.append(tree.left!)
}
if tree.right != nil {
tempList.append(tree.right!)
}
}
ans.append(valList)
treeList = tempList
}
return ans
}
  • Post title:102. 二叉树的层序遍历
  • Post author:xxxixxxx
  • Create time:2021-02-24 23:17:00
  • Post link:https://xxxixxx.github.io/2021/02/24/2000-019-102. 二叉树的层序遍历/
  • Copyright Notice:All articles in this blog are licensed under BY-NC-SA unless stating additionally.
 Comments