package main
import . "nc_tools"

//BFS迭代法,通法
func levelOrder( root *TreeNode ) [][]int {
    // write code here
    if root == nil {
        return [][]int{}
    }

    queue := []*TreeNode{}
    queue = append(queue, root)
    levels := [][]int{}

    for len(queue) > 0 {
        n := len(queue)
        level := []int{}

        for i := 0; i < n; i++ {
            root = queue[0]
            queue = queue[1: ]

            level = append(level, root.Val)
            if root.Left != nil {
                queue = append(queue, root.Left)
            }
            if root.Right != nil {
                queue = append(queue, root.Right)
            }
        }
        levels = append(levels, level)
    }
    return levels
}