题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
http://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
import . "nc_tools"
/*
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* @param pRoot TreeNode类
* @return int整型二维数组
*/
//BFS+队列
func Print( root *TreeNode ) [][]int {
// write code here
res := [][]int{}
if root == nil {return nil}
queue := []*TreeNode{root}
for len(queue) > 0 {
n := len(queue)
tmp := make([]int, n)
for i := 0; i < n; i++ {
if queue[i] == nil {
continue
}
if len(res)%2 == 0 {
tmp[i] = queue[i].Val
}else {
tmp[n-1-i] = queue[i].Val
}
if queue[i].Left != nil {
queue = append(queue, queue[i].Left)
}
if queue[i].Right != nil {
queue = append(queue, queue[i].Right)
}
}
queue = queue[n:]
res = append(res, tmp)
}
return res
}