題目:
題解:
/**
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
}