题解 | #从上往下打印二叉树# | Golang
从上往下打印二叉树
https://www.nowcoder.com/practice/7fe2212963db4790b57431d9ed259701
package main /* * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * @param root TreeNode类 * @return int整型一维数组 */ func PrintFromTopToBottom( root *TreeNode ) []int { ans := []int{} q := []*TreeNode{} if root != nil { q = append(q, root) } for len(q) != 0 { n := len(q) for ; n >= 1; n-- { front := q[0] ans = append(ans, front.Val) if front.Left != nil { q = append(q, front.Left) } if front.Right != nil { q = append(q, front.Right) } q = q[1:] } } return ans }