题解 | #把二叉树打印成多行# | Golang
把二叉树打印成多行
https://www.nowcoder.com/practice/445c44d982d04483b04a54f298796288
package main import . "nc_tools" /* * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param pRoot TreeNode类 * @return int整型二维数组 */ func Print( pRoot *TreeNode ) [][]int { ans := [][]int {} if pRoot == nil { return ans } queue := []*TreeNode{} queue = append(queue, pRoot) for len(queue)!=0 { item := []int{} n := len(queue) for ; n >= 1; n-- { front := queue[0] queue = queue[1:] item = append(item, front.Val) if front.Left != nil { queue = append(queue, front.Left) } if front.Right != nil { queue = append(queue, front.Right) } } ans = append(ans, item) } return ans }