题解 | #求二叉树的层序遍历#
求二叉树的层序遍历
http://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3
核心思想
需要对遍历树的每一层进行统计,计算出树的最大层数,然后将每一层的元素放到对应的切片中。由于树的遍历只有先序遍历(DLR),后序遍历(LRD)和中序遍历(LDR)三种模式,于是不存在直接基于这三种模式的层序遍历方案(因为这三种模式都会涉及不同层的节点)。故,最终方案是通过建立字典的方式,将每层的数据放到对应的动态数组中(在Golang语言中是切片),并按层的大小导入到要求的二维动态数组中。
func levelOrder( root *TreeNode ) [][]int {
// write code here
var data [][]int
dic:=make(map[int][]int,1500)
order(root,&dic)
for i:=0;;i++{
if dic[i]==nil{
break
}
data=append(data,dic[i])
}
return data
}
var a int=0
func order(root *TreeNode,dic *map[int][]int){
if root==nil{
return
}
(*dic)[a]=append((*dic)[a],root.Val)
a++
order(root.Left,dic)
order(root.Right,dic)
a--
}