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


/**
* 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 == nullptr){
return root;
}
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
TreeNode* tmp = q.front();
q.pop();
TreeNode* n = tmp->left;
tmp->left = tmp->right;
tmp->right = n;
if(tmp->left){
q.push(tmp->left);
}
if(tmp->right){
q.push(tmp->right);
}
}
return root;
}
};