题解 | #求二叉树的层序遍历#
求二叉树的层序遍历
http://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3
package main
import . "nc_tools"
/*
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
/**
*
* @param root TreeNode类
* @return int整型二维数组
*/
func levelOrder( root *TreeNode ) [][]int {
res := make([][]int, 0)
if root == nil {
return res
}
s := make([]*TreeNode, 0 , 10)
s = append(s, root)
for {
length := len(s)
if length > 0 {
curs := make([]int, 0)
curNodes := make([]*TreeNode, 0)
for i := 0; i < length ;i++ {
cur := s[i]
curs = append(curs, cur.Val)
if cur.Left != nil {
curNodes = append(curNodes, cur.Left)
}
if cur.Right != nil {
curNodes = append(curNodes, cur.Right)
}
}
s = curNodes
res = append(res, curs)
} else {
break
}
}
return res
}