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