# \[145]\[困难] 二叉树的后序遍历

## 题目描述

[145. 二叉树的后序遍历](https://leetcode-cn.com/problems/binary-tree-postorder-traversal/)

给定一个二叉树，返回它的 后序 遍历。

示例:

```
输入: [1,null,2,3]  
   1
    \
     2
    /
   3

输出: [3,2,1]
```

进阶: 递归算法很简单，你可以通过迭代算法完成吗？

## 解题思路

### 递归

```python
class Solution:
    def postorderTraversal(self, root: TreeNode) -> List[int]:
        res = []

        def dfs(node):
            if node is None:
                return
            dfs(node.left)
            dfs(node.right)
            res.append(node.val)

        dfs(root)
        return res
```

### 迭代

后续遍历顺序是**左右中**. 但如果我们按**中右左**的形式遍历, 得到的结果会与后续遍历的结果完全相反, 只需要将这种遍历方式得到的数组反转, 即得到后续遍历的结果.

前序遍历顺序是**中左右**, 与**中右左**相比只是先左和先右的问题, 参考[\[144\]\[中等\] 二叉树的前序遍历](https://kerasnoone.gitbook.io/garnet/suan-fa/shu/144-er-cha-shu-de-qian-xu-bian-li)的迭代方法.

```python
class Solution:
    def postorderTraversal(self, root: TreeNode) -> List[int]:
        if root is None:
            return []

        res, stack = [], [root]
        while stack:
            node = stack.pop(-1)

            res.append(node.val)
            if node.left is not None:
                stack.append(node.left)
            if node.right is not None:
                stack.append(node.right)
        return res[::-1]
```


---

# 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://kerasnoone.gitbook.io/garnet/suan-fa/shu/145-er-cha-shu-de-hou-xu-bian-li.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.
