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

## 题目

请实现一个函数按照之字形顺序打印二叉树，即第一行按照从左到右的顺序打印，第二层按照从右到左的顺序打印，第三行再按照从左到右的顺序打印，其他行以此类推。

例如:

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

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

返回其层次遍历结果：

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

提示：

节点总数 <= 1000

来源：力扣（LeetCode）

链接：<https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-iii-lcof>

著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。

## 题解

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

    var queue: [TreeNode] = []
    var queueB: [TreeNode] = []
    var toBePrint = 0
    var nextLevelCount = 0
    var result: [[Int]] = []
    var flag = true

    queue.append(r)
    toBePrint += 1

    var temp = Array(repeating: 0, count: queue.count)

    while queue.isEmpty == false {
        let first = queue.removeFirst()
        temp[flag ? (temp.count - toBePrint) : (toBePrint - 1)] = first.val
        toBePrint -= 1

        if let left = first.left {
            queueB.append(left)
            nextLevelCount += 1
        }

        if let right = first.right {
            queueB.append(right)
            nextLevelCount += 1
        }

        if toBePrint == 0 {
            result.append(temp)
            queue = queueB
            temp = Array(repeating: 0, count: nextLevelCount)

            toBePrint = nextLevelCount
            nextLevelCount = 0
            queueB = []
            flag.toggle()
        }
    }

    return result
}
```

![3](/files/-MiWFVp_YLMnd29fawnz)


---

# 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/32iii.-cong-shang-dao-xia-da-yin-er-cha-shu-iii.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.
