题解 | #求二叉树的层序遍历#
求二叉树的层序遍历
http://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3
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 }