一大早起来练习基础算法,今天练习下二叉树的层序遍历,对应leetcode第102题
给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。
输入:root = [3,9,20,null,null,15,7]
输出:[[3],[9,20],[15,7]]
输入:root = [1]
输出:[[1]]
以下是我的代码实现
package main
import (
"fmt"
"testing"
)
// TreeNode represents a node in a binary tree
type (
TreeDocument struct {
Val int
Left *TreeDocument
Right *TreeDocument
}
)
func loopLayerArr(root *TreeDocument) [][]int {
queues := []*TreeDocument{root}
result := make([][]int, 0)
for len(queues) > 0 {
queueSize := len(queues)
layerArr := make([]int, queueSize)
for i := 0; i < queueSize; i++ {
queue := queues[0]
layerArr[i] = queue.Val
if queue.Left != nil {
queues = append(queues, queue.Left)
}
if queue.Right != nil {
queues = append(queues, queue.Right)
}
queues = queues[1:]
}
result = append(result, layerArr)
}
return result
}
func TestLayerLoop(t *testing.T) {
// 构建一个示例二叉树
root := &TreeDocument{
Val: 3,
Left: &TreeDocument{
Val: 9,
Left: &TreeDocument{
Val: 7,
},
Right: &TreeDocument{
Val: 8,
},
},
Right: &TreeDocument{
Val: 20,
Left: &TreeDocument{
Val: 15,
},
Right: &TreeDocument{
Val: 7,
},
},
}
result := loopLayerArr(root)
fmt.Println("result => ", result)
}
代码比较简单,仅供参考和自己后续的回顾