给定一个二叉树,返回该二叉树层序遍历的结果,(从左到右,一层一层地遍历)
例如:
给定的二叉树是{3,9,20,#,#,15,7},
该二叉树层序遍历的结果是
[
[3],
[9,20],
[15,7]
]
思路:用一个树节点堆来存储每一层的节点,下一层的节点就是这些节点抛出,把他们的子节点再写入这个切片,根据每一层的数量来控制层次的节点分割
package main
import . "nc_tools"
/*
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
/**
*
* @param root TreeNode类
* @return int整型二维数组
*/
func levelOrder( root *TreeNode ) [][]int {
// write code here
if root == nil {
return nil
}
var ret [][]int
var treeList []*TreeNode
treeList = append(treeList, root)
for len(treeList) > 0 {
//取出一层的数量
var levelList []int
num := len(treeList)
for num > 0 {
node := treeList[0]
levelList = append(levelList, node.Val)
if node.Left != nil {
treeList = append(treeList, node.Left)
}
if node.Right != nil {
treeList = append(treeList, node.Right)
}
treeList = treeList[1:]
num --
}
ret = append(ret, levelList)
}
return ret
}