Force button topic link
Given a binary tree, return the values of nodes traversed in order. (That is, layer by layer, all nodes are accessed from left to right).
That is, return a two-dimensional array.
Implementation (iteration, commit pass)
import "container/list"
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */
func levelOrder(root *TreeNode)[] []int {
if root == nil {
return nil
}
var (
res [][]int
q = NewQueue()
)
q.Push(root)
for! q.IsEmpty() { c := q.Len() level :=make([]int.0, c)
for i := 0; i < c; i++ {
node := q.Pop().(*TreeNode)
level = append(level, node.Val)
ifnode.Left ! =nil {
q.Push(node.Left)
}
ifnode.Right ! =nil {
q.Push(node.Right)
}
}
res = append(res, level)
}
return res
}
type Queue struct {
l *list.List
}
func NewQueue(a) *Queue {
return &Queue{
l: list.New(),
}
}
func (o *Queue) Push(v interface{}) {
o.l.PushBack(v)
}
func (o *Queue) Pop(a) interface{} {
if o.IsEmpty() {
panic("Queue is empty")
}
e := o.l.Front()
o.l.Remove(e)
return e.Value
}
func (o *Queue) Front(a) interface{} {
if o.IsEmpty() {
panic("Queue is empty")}return o.l.Front().Value
}
func (o *Queue) Back(a) interface{} {
if o.IsEmpty() {
panic("Queue is empty")}return o.l.Back().Value
}
func (o *Queue) IsEmpty(a) bool {
return o.l.Len() == 0
}
func (o *Queue) Len(a) int {
return o.l.Len()
}
Copy the code