# 题目链接
# 题目描述
从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
# 解题思路
1,首先创建一个queue队列,根节点入队 2,遍历queue,遍历的值加入切片的同一行(为了同一层节点在二维切片的同一行),再看该节点有没有左右子树,若有,先后假如temp临时队列。再将queue = temp,相当于原有元素出队,新加元素入队 3,queue不为空,继续遍历
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func levelOrder(root *TreeNode) [][]int {
var res [][]int
if root == nil {
return res
}
//利用队列
queue := []*TreeNode{root}
var level int = 0
for len(queue) != 0 {
//利用临时队列,暂存每个节点的左右子树
temp := []*TreeNode{}
//只需考虑在同一层上追加元素
res = append(res,[]int{})
//遍历队列,追加队列元素到切片同一层,追加队列元素左右子树到临时队列
for _,v := range queue {
res[level] = append(res[level],v.Val)
if v.Left != nil {
temp = append(temp,v.Left)
}
if v.Right != nil{
temp = append(temp,v.Right)
}
}
//层级加1,队列重新复制为队列的左右子树集
level++
//队列赋值
queue = temp
}
return res
}
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
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