# Leetcode 226. Invert Binary Tree
###### tags: `leetcode` `daily` `Tree`
[題目連結](https://leetcode.com/problems/invert-binary-tree/)
# Method
:::info
:bulb: **作法講解**:
use DFS algorithm traverse all of the node,
for each node,
if node is NULL, directly return NULL.
if node not NULL,
traverse left child of node, return node called "left_node"
traverse right child of node, return node called "right_node"
set left child of node to "right_node"
set right child of node to "left_node"
:::
TC: O(N) SC: O(h)
:::spoiler 完整程式碼
```cpp=
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root == NULL) {
return root;
}
TreeNode *left = root->left;
TreeNode *right = root->right;
root->left = invertTree(right);
root->right = invertTree(left);
return root;
}
};
```
:::