[Leetcode]5.III. 从上到下打印二叉树 III
题目:请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[20,9],
[15,7]
]
思想:和上题一样,在遍历一层后,增加一个奇偶层判定,同时将该层的数据存到一个tempdata数组中,如果为偶数层,则先反转数组再append,否则直接append.
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func levelOrder(root *TreeNode) [][]int {
var queue []*TreeNode
var res [][]int
if root == nil {
return res
}
queue = append(queue,root)
var i int = 0
for len(queue)!=0{
var temp []*TreeNode
var tempdata []int
res = append(res,[]int{})
for _,v:=range queue{
tempdata=append(tempdata,v.Val)
if v.Left != nil{
temp = append(temp,v.Left)
}
if v.Right !=nil{
temp = append(temp,v.Right)
}
}
queue = queue[0:0]
if i%2 ==1{
for k:=0;k<len(tempdata)/2;k++{
t := tempdata[k]
tempdata[k]=tempdata[len(tempdata)-1-k]
tempdata[len(tempdata)-1-k]=t
}
}
for l:=0;l<len(tempdata);l++{
res[i] = append(res[i],tempdata[l])
}
i++
queue = temp
}
return res
}
题目来源:https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-iii-lcof/

浙公网安备 33010602011771号