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
| /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func levelOrder(root *TreeNode) [][]int { var ans [][]int var dfs func(*TreeNode, int) dfs = func(node *TreeNode, depth int) { if node == nil { return } if len(ans) <= depth { ans = append(ans, []int{}) } ans[depth] = append(ans[depth], node.Val) dfs(node.Left, depth+1) dfs(node.Right, depth+1) } dfs(root, 0) return ans }
|