题解 | #求二叉树的层序遍历#
求二叉树的层序遍历
https://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3
package main
import . "nc_tools"
/*
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型二维数组
*/
func levelOrder(root *TreeNode) [][]int {
list := make([][]int, 0)
Level(root, &list, 1)
return list
}
// append扩容导致导致生成新数组
func Level(root *TreeNode, list *[][]int, depth int) {
if root == nil {
return
}
if len(*list) < depth {
*list = append(*list, []int{root.Val})
} else {
(*list)[depth-1] = append((*list)[depth-1], root.Val)
}
depth++
Level(root.Left, list, depth)
Level(root.Right, list, depth)
}
