> For the complete documentation index, see [llms.txt](https://jenhsuan.gitbook.io/algorithm/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jenhsuan.gitbook.io/algorithm/leetcode/226.-invert-binary-tree.md).

# 226. Invert Binary Tree

## 1.問題

* 反轉binary tree

![](/files/-LJ6pJsmngjJ1wX6eax4)

## 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

![](/files/-LJ6pM3rrpIrG__a2OGg)
