# Invert binary tree, runtime error

• class Solution {

public:
TreeNode* invertTree(TreeNode* root) {

``````    if(root==NULL)
return root;
if(root->left!=NULL || root->right!=NULL)
swap(root);

return root;
}
``````

private:
void swap(TreeNode* r){

``````    TreeNode* temp=r->left;
r->left=r->right;
r->right=temp;

auto L=r->left;
auto R=r->right;

if(L!=NULL && L->left!=NULL || L->right!=NULL)
swap(L);
if(R!=NULL && R->left!=NULL || R->right!=NULL)
swap(R);
}
``````

};

where am i wrong? thanks

Now, I have solved the problem by changing the last two if(..) codes to if(L!=NULL && ( L->left!=NULL || L->right!=NULL) ) and if(R!=NULL && (R->left!=NULL || R->right!=NULL) )
because of the && and || ------the different priority !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

• these lines :

`````` if(L!=NULL && L->left!=NULL || L->right!=NULL)
swap(L);
if(R!=NULL && R->left!=NULL || R->right!=NULL)
swap(R);
``````

suppose , in left subtreee(L) left node is not null and right is Null then below condition get true
if(L!=NULL && L->left!=NULL || L->right!=NULL)

and there is no NULL check when you pass swap(L) in swap function thus , the error

and you should be calling Invertfunction

I modified your solution and it got accepted.

class Solution {

public: TreeNode* invertTree(TreeNode* root) {

``````if(root==NULL)
return root;
if(root->left!=NULL || root->right!=NULL)
swap(root);

return root;
``````

}
private: void swap(TreeNode* r){

``````TreeNode* temp=r->left;
r->left=r->right;
r->right=temp;

auto L=r->left;
auto R=r->right;
invertTree(L);
invertTree(R);
``````

}
};

My C code was :

struct TreeNode* invertTree(struct TreeNode* root) {

``````if(root==NULL)
return root;

struct TreeNode* tmp=NULL;
tmp=root->left;
root->left=root->right;
root->right=tmp;

invertTree(root->left);
invertTree(root->right);

return root;
``````

}

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.