1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| /** * Definition for a Node. * type Node struct { * Val int * Children []*Node * } */
func levelOrder(root *Node) [][]int { ans := [][]int{} var dfs func(node *Node, depth int) dfs = func(node *Node, depth int) { if node == nil { return } if len(ans) <= depth { ans = append(ans, []int{}) } ans[depth] = append(ans[depth], node.Val) depth++ for _, child := range node.Children { dfs(child, depth) } } dfs(root, 0) return ans }
|