题解 | #二叉树的深度#
按之字形顺序打印二叉树
http://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
package main
import . "nc_tools"
/*
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func Print(root *TreeNode ) [][]int {
ans := make([][]int, 0)
if root == nil {
return ans
}
queue := make([]*TreeNode, 0)
queue = append(queue, root)
for len(queue) > 0 {
subNum := make([]int, 0)
size := len(queue)
for size > 0 {
cur := queue[0]
queue = queue[1:]
if len(ans) % 2 == 0 {
subNum = append(subNum, cur.Val)
}else {
//insert a value in a slice at a given index
subNum = append(subNum, 0)
copy(subNum[1:], subNum[0:])
subNum[0] = cur.Val
}
if cur.Left != nil {
queue = append(queue, cur.Left)
}
if cur.Right != nil {
queue = append(queue, cur.Right)
}
size--
}
ans = append(ans, subNum)
}
return ans
}