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