> For the complete documentation index, see [llms.txt](https://leetcodebook-1.gitbook.io/top-interview-150/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://leetcodebook-1.gitbook.io/top-interview-150/tree/binary-tree-level-order-traversal.md).

# 二叉树的层序遍历

题目链接: <https://leetcode.cn/problems/binary-tree-level-order-traversal>

## 解题思路：

1. 遍历每层节点，并将每个非`nil`的节点存入临时队列，
2. 遍历完当前层节点后，将临时队列中的节点存入`queue`，并将当层节点的值存入`result`中

```go
/**
 * 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
	}
	res := make([][]int, 0)
	queue := []*TreeNode{root}
	for len(queue) > 0 {
		tmpArr := make([]*TreeNode, 0)
		tmpRes := make([]int, len(queue))
		for idx, node := range queue {
			tmpRes[idx] = node.Val
			if node.Left != nil {
				tmpArr = append(tmpArr, node.Left)
			}
			if node.Right != nil {
				tmpArr = append(tmpArr, node.Right)
			}
		}
		res = append(res, tmpRes)
		queue = tmpArr
	}
	return res
}
```

## 复杂度分析

* **时间复杂度：** 时间复杂度为$$O(n)$$，$$n$$的大小为树的节点数量
* **空间复杂度：** 空间复杂度为$$O(n)$$


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://leetcodebook-1.gitbook.io/top-interview-150/tree/binary-tree-level-order-traversal.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
