# Invert Binary Tree

## Question

Invert a binary tree.

Example
1         1
/ \       / \
2   3  => 3   2
/       \
4         4
Challenge
Do it in recursion is acceptable, can you do it without recursion?


## 題解1 - Recursive

### C++ - return void

/**
* Definition of TreeNode:
* class TreeNode {
* public:
*     int val;
*     TreeNode *left, *right;
*     TreeNode(int val) {
*         this->val = val;
*         this->left = this->right = NULL;
*     }
* };
*/
class Solution {
public:
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
void invertBinaryTree(TreeNode *root) {
if (root == NULL) return;
swap(root->left, root->right);
invertBinaryTree(root->left);
invertBinaryTree(root->right);
}
};


### C++ - return TreeNode *

/**
* 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 NULL;

TreeNode *temp = root->left;
root->left = invertTree(root->right);
root->right = invertTree(temp);

return root;
}
};


## 題解2 - Iterative

### C++

/**
* Definition of TreeNode:
* class TreeNode {
* public:
*     int val;
*     TreeNode *left, *right;
*     TreeNode(int val) {
*         this->val = val;
*         this->left = this->right = NULL;
*     }
* };
*/
class Solution {
public:
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
void invertBinaryTree(TreeNode *root) {
if (root == NULL) return;

queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
// pop out the front node
TreeNode *node = q.front();
q.pop();
// swap between left and right pointer
swap(node->left, node->right);
// push non-NULL node
if (node->left != NULL) q.push(node->left);
if (node->right != NULL) q.push(node->right);
}
}
};