---
description: https://leetcode.com/problems/invert-binary-tree/description/
---

# 226. Invert Binary Tree

Invert a binary tree.

**Example:**

Input:

```
     4
   /   \
  2     7
 / \   / \
1   3 6   9
```

Output:

```
     4
   /   \
  7     2
 / \   / \
9   6 3   1
```

**Trivia:**\
This problem was inspired by [this original tweet](https://twitter.com/mxcl/status/608682016205344768) by [Max Howell](https://twitter.com/mxcl):

> Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so f\*\*\* off.

## Thoughts

看到二叉树就先想分治，假设左右子树已经翻转，那在root把左右子树掉个个即可。\
注意要把左右子树先存起来，别直接把调完的fit进新调用。

## Code

```
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode invertTree(TreeNode root) {
        if (root == null) {
            return null;
        }

        TreeNode left = invertTree(root.left);
        TreeNode right = invertTree(root.right);

        root.left = right;
        root.right = left;

        return root;
    }
}
```

## Analysis

时间复杂度为节点树O(n)

## Ver. 2

用stack的traversal实现. 时间O(N), 空间O(h).

```python
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if (root == NULL) return root;
        stack<TreeNode*> s;
        s.push(root);
        while (!s.empty()) {
            auto i = s.top();
            s.pop();
            if (i->left != NULL) s.push(i->left);
            if (i->right != NULL) s.push(i->right);
            const auto t = i->left;
            i->left = i->right;
            i->right = t;
        }
        return root;
    }
};
```

## Functional

> 这段代码体现的思维，就是旧树到新树的映射——对一颗二叉树而言，它的镜像树就是左右节点递归镜像的树。
>
> 这段代码最终达到的目的同样是翻转二叉树，但是它得到结果的方式和 python 代码有着本质的差别：通过描述一个 旧树->新树 的映射，而不是描述“从旧树得到新树应该怎样做”来达到目的。

```python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def invertTree(self, root: TreeNode) -> TreeNode:
        if not root: return None
        return TreeNode(root.val, self.invertTree(root.right), self.invertTree(root.left))
```

[https://hcyue.me/2016/05/14/%E4%BB%80%E4%B9%88%E6%98%AF%E5%87%BD%E6%95%B0%E5%BC%8F%E7%BC%96%E7%A8%8B%E6%80%9D%E7%BB%B4/](https://hcyue.me/2016/05/14/%E4%BB%80%E4%B9%88%E6%98%AF%E5%87%BD%E6%95%B0%E5%BC%8F%E7%BC%96%E7%A8%8B%E6%80%9D%E7%BB%B4/)
