Invert a binary tree.
4
/ \ 2 7
/ \ / \ 1 3 6 9
to
4
/ \ 7 2
/ \ / \ 9 6 3 1
BFS:
/** * 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 root;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
TreeNode* cur = q.front();
q.pop();
TreeNode* tmp = cur->left;
cur->left = cur->right;
cur->right = tmp;
if (cur->left) q.push(cur->left);
if (cur->right) q.push(cur->right);
}
return root;
}
};
There is a simple recursion solution:
TreeNode* invertTree(TreeNode* root) {
if (root==NULL) return NULL;
TreeNode* tmp = root->left;
root->left = invertTree(root->right);
root->right = invertTree(tmp);
return root;
}
Be careful for the NULL pointer!
When you use a pointer, please make sure that it is availble!