剑指 Offer 32. 从上到下打印二叉树
题目描述:
使用层序遍历,遍历二叉树的三种题目。
[I] 从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。
[II] 从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
[III] 请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。
考察重点:着重注意题目3,使用Golang中的list数据结构,作为队列进行层次遍历。
第一题
func levelOrder(root *TreeNode) []int {if root == nil{return []int{}}res := make([]int, 1)list := make([]*TreeNode, 1)list[0] = rootnowList, nextList := 0, 1for {i := nowListnowList = nextListfor ; i < nowList; i++ {res = append(res, list[i].Val)print(list[i].Val)if list[i].Left != nil {list = append(list, list[i].Left)nextList++}if list[i].Right != nil {list = append(list, list[i].Right)nextList++}}if nowList == nextList {return res[1:]}}
}
第二题
func levelOrder(root *TreeNode) [][]int {if root == nil{return [][]int{}}res := [][]int{}list := make([]*TreeNode, 1)list[0] = rootnowList, nextList := 0, 1for {i := nowListnowList = nextListtRes := []int{}for ; i < nowList; i++ {tRes = append(tRes, list[i].Val)print(list[i].Val)if list[i].Left != nil {list = append(list, list[i].Left)nextList++}if list[i].Right != nil {list = append(list, list[i].Right)nextList++}}res = append(res, tRes)if nowList == nextList {return res}}
}
第三题
func levelOrder(root *TreeNode) [][]int {if root == nil {return [][]int{}}res := [][]int{}rList := list.New()rList.PushBack(root)mark := falsefor rList.Len() != 0 {tLen := rList.Len()tRes := []int{}tList := list.New()if mark {for ; tLen > 0; tLen-- {nowT := rList.Front().Value.(*TreeNode)tRes = append(tRes, nowT.Val)if nowT.Right != nil {tList.PushBack(nowT.Right)}if nowT.Left != nil {tList.PushBack(nowT.Left)}rList.Remove(rList.Front())}mark = false} else {for ; tLen > 0; tLen-- {nowT := rList.Front().Value.(*TreeNode)tRes = append(tRes, nowT.Val)if nowT.Left != nil {tList.PushBack(nowT.Left)}if nowT.Right != nil {tList.PushBack(nowT.Right)}rList.Remove(rList.Front())}mark = true}for tList.Len() != 0 {rList.PushBack(tList.Back().Value.(*TreeNode))tList.Remove(tList.Back())}res = append(res, tRes)}return res
}