# 226. Invert Binary Tree

## 1.問題

* 反轉binary tree

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LJ6dPEAS2mSJt_yD0fZ%2F-LJ6pJsmngjJ1wX6eax4%2F2018080501.jpg?alt=media\&token=ecd96301-cddf-4540-96c1-af3f07d7bb38)

## 2.想法

* Recursion + swap
  * 由下到上, 交換child node

## 3.程式碼

```
/**
 * 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) {
            return root;
        }
        
        return swap(root);
    }
private:
    TreeNode* swap(TreeNode* root) {
        if (!root) {
            return root;
        }
        
        TreeNode* tmp = swap(root->left);
        root->left = swap(root->right);
        root->right = tmp;
        
        return root;
    }
};
```

## 4.Performance

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LJ6dPEAS2mSJt_yD0fZ%2F-LJ6pM3rrpIrG__a2OGg%2F2018080502.jpg?alt=media\&token=7a10c626-fc6f-4a4d-bf24-87b4f33eaf98)
