原二叉树:
3
/ \
9 20
/ \
15 7
要求遍历结果:
[
[3],
[9,20],
[15,7]
]
代码及注释
package main
import "fmt"
func main() {
root := buildTree()
fmt.Println(levelOrder(root))
}
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func levelOrder(root *TreeNode) [][]int {
if root == nil {
return nil
}
res := [][]int{}
cLevelNodes := []*TreeNode{root}
for i := 0; len(cLevelNodes) > 0; i++ {
res = append(res, []int{})
nLevelNodes := []*TreeNode{}
for j := 0; j < len(cLevelNodes); j++ {
res[i] = append(res[i], cLevelNodes[j].Val)
if cLevelNodes[j].Left != nil {
nLevelNodes = append(nLevelNodes, cLevelNodes[j].Left)
}
if cLevelNodes[j].Right != nil {
nLevelNodes = append(nLevelNodes, cLevelNodes[j].Right)
}
}
cLevelNodes = nLevelNodes
}
return res
}
func buildTree() *TreeNode {
return &TreeNode{
Val: 3,
Left: &TreeNode{
Val: 9,
Left: nil,
Right: nil,
},
Right: &TreeNode{
Val: 20,
Left: &TreeNode{
Val: 15,
Left: nil,
Right: nil,
},
Right: &TreeNode{
Val: 7,
Left: nil,
Right: nil,
},
},
}
}