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

## 前言

二叉树的常规便利： `前序遍历` 、 `中序遍历` 、 `后序遍历` 可能都已经非常熟悉了。

本文将结合一个题目的三种形态来玩一下花式遍历。

## 一、 顺序打印

### 1.1 题目

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

例如:

给定二叉树: \[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)

### 1.2 分析

由于二叉树并非一个有序队列，但题目要求我们有序的输出。此时可以考虑借助一个辅助队列进行解题。

通过分析我们可以找到规律：每次打印一个节点的时候，如果该节点存在子节点，则把该节点的子节点插入队列末尾。接下来从队列头部取出节点重复打印操作。直至所有节点打印完成。

| 当前节点 | 辅助队列 |      结果     |
| :--: | :--: | :---------: |
|   3  | 9,20 |      3      |
|   9  |  20  |     3,9     |
|  20  | 15,7 |    3,9,20   |
|  15  |   7  |  3,9,20,15  |
|   7  |   -  | 3,9,20,15,7 |

### 1.3 编码

```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)

## 二、 逐行打印

### 2.1 题目

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

例如:

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

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

返回其层次遍历结果：

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

### 2.2 分析

在第一种遍历的基础上，这本题加上了换行的逻辑。我们只需要加上换行的判断逻辑就可以了。

### 2.3 题解

```swift
func levelOrder(_ root: TreeNode?) -> [[Int]] {
    var queue: [TreeNode] = []
    /// 当前行需要继续打印的数量
    var toBePrint = 0
    /// 下一行的数量
    var nextLevelCount = 0
    var result: [[Int]] = []
    var temp: [Int] = []

    if let r = root {
        queue.append(r)
        toBePrint += 1
    }

    while queue.isEmpty == false {
        if let first = queue.first {
            temp.append(first.val)
            queue.removeFirst()
            toBePrint -= 1

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

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

            if toBePrint == 0 {
                result.append(temp)
                temp = []

                toBePrint = nextLevelCount
                nextLevelCount = 0
            }
        }
    }

    return result
}
```

![2](/files/-MiWFVf5-yv8n4vU2v9P)

## 三、 之字形打印

### 3.1 题目

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

例如:

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

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

返回其层次遍历结果：

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

### 3.2 易错点

本题很容易想当然的觉得和第二种差不多，`左右`换成`右左`就可以了嘛～于是稍微改一改就写出下面的代码：

```swift
func levelOrder(_ root: TreeNode?) -> [[Int]] {
    var queue: [TreeNode] = []
    var toBePrint = 0
    var nextLevelCount = 0
    var result: [[Int]] = []
    var temp: [Int] = []

    var flag = false

    if let r = root {
        queue.append(r)
        toBePrint += 1
    }

    while queue.isEmpty == false {
        if let first = queue.first {
            temp.append(first.val)
            queue.removeFirst()
            toBePrint -= 1

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

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

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

            if toBePrint == 0 {
                result.append(temp)
                temp = []

                toBePrint = nextLevelCount
                nextLevelCount = 0

                flag.toggle()
            }
        }
    }

    return result
}
```

然后顺序就乱掉了：

![4](/files/-MiWFWqZcwjMXt4LMBc4)

### 3.3 分析

这里不将思维局限于遍历的方向。这里还是按顺序逐层便利。一个队列A存放当前行，一个队列B存放下一行的。当一行遍历完，将B赋值给A，再用B来存放下一行。而打印结果则根据当前行的方向决定是从头插入还是从末尾插入。

### 3.4 题解

```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/32.-cong-shang-dao-xia-hua-shi-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.
