I solved this problem.
Invert a binary tree.
4 / \ 2 7 / \ / \ 1 3 6 9
To this
4 / \ 7 2 / \ / \ 9 6 3 1
This problem looked a lot harder at first and then I was able to come up with a recursive solution to this.
/**
* 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) || (root->left == NULL && root->right == NULL) )
{
return root;
}
TreeNode *temp = root->left;
root->left = root->right;
root->right = temp;
invertTree(root->left);
invertTree(root->right);
return root;
}
};
When I submitted this solution, I found that my submission ran faster than just 0.2 % of other submission for this problem.
Is there a better and faster approach to this, maybe an iterative one?