I have written this code to invert a binary tree.
Thus if the original tree is:
Then the tree returned should be:
/**
* 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;
/* Performing post-order traversal of the tree */
//Visiting the left node first
if(root->left != NULL)
invertTree(root->left);
//Visiting the right node next
if(root->right != NULL)
invertTree(root->right);
//Visiting the current node; swapping the left and the right nodes of the current node
TreeNode* tn = new TreeNode(0);
tn=root->right;
root->right=root->left;
root->left=tn;
return root;
}
};
While the code runs correctly and returns the required output, I think I am invoking undefined behavior when the control hits the leaf nodes. Since, at the leaf, a new node is created and it is assigned (incorrectly) the right of the current node and so on.
Could someone please clarify if what I am doing is indeed wrong?
Note: The question and the images are taken from LeetCode.com