102. 二叉树的层序遍历

从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。

例如:
给定二叉树: [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回其层次遍历结果:

[
  [3],
  [9,20],
  [15,7]
]

提示:

  1. 节点总数 <= 1000

注意:本题与主站 102 题相同:https://leetcode-cn.com/problems/binary-tree-level-order-traversal/

题解:

使用队列的方式

func levelOrder(root *TreeNode) [][]int {
	var res [][]int
	if root == nil {
		return res
	}
	queue := []*TreeNode{root}
	//层级
	var level = 0
	for len(queue) != 0 {
		//临时队列,暂存每个节点的左右子树
		var 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
}