题目:
题解:
/**
102. 二叉树的递归遍历*/
func levelOrder(root *TreeNode) [][]int {arr := [][]int{}depth := 0var order func(root *TreeNode, depth int)order = func(root *TreeNode, depth int) {if root == nil {return}if len(arr) == depth {arr = append(arr, []int{})}arr[depth] = append(arr[depth], root.Val)order(root.Left, depth+1)order(root.Right, depth+1)}order(root, depth)return arr
}/**
102. 二叉树的层序遍历*/
func levelOrder(root *TreeNode) [][]int {res:=[][]int{}if root==nil{//防止为空return res}queue:=list.New()queue.PushBack(root)var tmpArr []intfor queue.Len()>0 {length:=queue.Len()//保存当前层的长度,然后处理当前层(十分重要,防止添加下层元素影响判断层中元素的个数)for i:=0;i<length;i++{node:=queue.Remove(queue.Front()).(*TreeNode)//出队列if node.Left!=nil{queue.PushBack(node.Left)}if node.Right!=nil{queue.PushBack(node.Right)}tmpArr=append(tmpArr,node.Val)//将值加入本层切片中}res=append(res,tmpArr)//放入结果集tmpArr=[]int{}//清空层的数据}return res
}