When i’m doing a dry run I’m getting the right result but I can’t understand why its showing a runtime error on leetcode.
Here’s my code-
When i’m doing a dry run I’m getting the right result but I can’t understand why its showing a runtime error on leetcode.
Here’s my code-
Hey @nidhigupta847
if(prev==NULL)
{ head=root;
}
else
{
root->left=prev;(LINE1)
prev->right=root;
}
prev=root;
preo(root->left);(Line 2)
preo(root->right);
ur code is not even working for
…1
.2 null
In line 1 u are making left of root as prev and in line 2 making recursive call to root->left which makes it go in infinite loop.
Here follow this for correct implementation
` void flatten(struct Node* root)
{
// base condition- return if root is NULL
// or if it is a leaf node
if (root == NULL || root->left == NULL &&
root->right == NULL) {
return;
}
// if root->left exists then we have
// to make it root->right
if (root->left != NULL) {
// move left recursively
flatten(root->left);
// store the node root->right
struct Node* tmpRight = root->right;
root->right = root->left;
root->left = NULL;
// find the position to insert
// the stored value
struct Node* t = root->right;
while (t->right != NULL) {
t = t->right;
}
// insert the stored value
t->right = tmpRight;
}
// now call the same function
// for root->right
flatten(root->right);
}`
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.