使用队列 q,以切片末尾作为队尾,以切片最小索引作为队首, 每次 q 出队队首元素,进行判断,并将左右子节点加入队尾
func levelOrder(root *TreeNode) []int {
q := make([]*TreeNode, 0)
ans := []int{}
if root != nil {
q = append(q, root)
}
for len(q) != 0 {
// 出队队首元素
top := q[0]
q = q[1:]
ans = append(ans, top.Val)
// 如果左右儿子存在,入队
if top.Left != nil {
q = append(q, top.Left)
}
if top.Right != nil {
q = append(q, top.Right)
}
}
return ans
}