# 32.I.从上到下打印二叉树

## 题目

从上到下打印出二叉树的每个节点，同一层的节点按照从左到右的顺序打印。

例如:

给定二叉树: \[3,9,20,null,null,15,7],

```
     3
    / \
   9  20
     /  \
    15   7
```

返回：

```
[3,9,20,15,7]
```

提示：

节点总数 <= 1000

来源：[力扣（LeetCode）](https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-lcof)

## 题解

```swift
func levelOrder(_ root: TreeNode?) -> [Int] {
    guard let r = root else { return [] }
    var result: [Int] = []
    var queue: [TreeNode] = [r]

    while queue.isEmpty == false {
        let first = queue[0]
        result.append(first.val)

        if let left = first.left {
            queue.append(left)
        }

        if let right = first.right {
            queue.append(right)
        }

        queue.removeFirst()
    }

    return result
}
```

![1](/files/-MiWFVVfrUkcUt07CeWe)


---

# Agent Instructions: 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://ryukiedev.gitbook.io/wiki/shu-ju-jie-gou-yu-suan-fa/jian-zhi-offerswift/32i.-cong-shang-dao-xia-da-yin-er-cha-shu.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.
