leetcode 102.二叉树的层级遍历 golang实现
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func BFS(root *BinaryTree) []int {
valueList := make([]int, 0)
queue := make([]*BinaryTree, 0)
if root == nil{
return valueList
}
queue = append(queue, root)
for len(queue) > 0 {
first := queue[0]
valueList = append(valueList, first.Value)
queue = queue[1:]
if first.Left != nil {
queue = append(queue, first.Left)
}
if first.Right != nil {
queue = append(queue, first.Right)
}
}
return valueList
}
func BFSLevelOrder(root *TreeNode) [][]int {
queue := make([]*TreeNode, 0)
valueList := make([][]int, 0)
if root == nil{
return valueList
}
queue = append(queue, root)
for len(queue) > 0 {
tmpQueue := make([]*TreeNode, 0)
tmpValueList := make([]int, 0)
for len(queue) > 0 {
first := queue[0]
queue = queue[1:]
tmpValueList = append(tmpValueList, first.Val)
if first.Left != nil {
tmpQueue = append(tmpQueue, first.Left)
}
if first.Right != nil {
tmpQueue = append(tmpQueue, first.Right)
}
}
queue = queue[0:0]
queue = append(queue, tmpQueue...)
valueList = append(valueList, tmpValueList)
}
return valueList
}