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
| func levelOrder(root *TreeNode) [][]int { res := make([][]int, 0) if root == nil { return res }
queue := make([]*TreeNode, 0) queue = append(queue, root)
for len(queue) > 0 { size := len(queue) level := make([]int, 0) for i := 0; i < size; i++ { node := queue[0] queue = queue[1:] level = append(level, node.Val) if node.Left != nil { queue = append(queue, node.Left) } if node.Right != nil { queue = append(queue, node.Right) } } res = append(res, level) } return res }
|