# Getting a runtime error on input {1,#,2}

• ``````class Solution {
public:
void flatten(TreeNode *root) {
flattenHelper(root);
}

TreeNode* flattenHelper(TreeNode* n) {
if (n == NULL) {
return NULL;
}
TreeNode* right_subtree = n->right;
TreeNode* left_subtree = n->left;
TreeNode* left_tail = NULL;
TreeNode* right_tail = NULL;

if (left_subtree != NULL) {
left_tail = flattenHelper(left_subtree);
n->right = left_subtree;
left_subtree->right = right_subtree;
}
if (right_subtree != NULL) {
right_tail = flattenHelper(right_subtree);
return right_tail;
} else {
return (left_tail != NULL ? left_tail : n);
}
}
};``````

• I tried it on my local machine, it ran fine. Does any one have an idea what is going on here ?

• I am also facing the same issue... I also ran the code on my local machine..

• ``````/**
* Definition for binary tree
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void flatten(TreeNode *root) {

if(root == NULL){
return ;
}

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

if(root->left != NULL ){
TreeNode *temp = root->right;
root->right = root->left;
while(root->right){
root = root->right;
}
root->right = temp;
}

}
};
``````

This is my code... runtime error on 1#2

• I went ahead with the following solution but still I dont understand the failure on 1#2

class Solution {
public:
void flatten(TreeNode *root) {
//flattenHelper(root);
if (root == NULL) {
return;
}

``````    flatten(root->left);
flatten(root->right);

TreeNode* p = root->left;
while(p && p->right != NULL) {
p = p->right;
}
if (p != NULL) {
p->right = root->right;
root->right = root->left;
root->left = NULL;
}
}

TreeNode* flattenHelper(TreeNode* n) {
if (n == NULL) {
return NULL;
}
TreeNode* right_subtree = n->right;
TreeNode* left_subtree = n->left;
TreeNode* left_tail = NULL;
TreeNode* right_tail = NULL;

if (left_subtree != NULL) {
left_tail = flattenHelper(left_subtree);
n->right = left_subtree;
left_subtree->right = right_subtree;
}
if (right_subtree != NULL) {
right_tail = flattenHelper(right_subtree);
return right_tail;
} else {
return (left_tail != NULL ? left_tail : n);
}
}
``````

};

• if(root->left != NULL ){
TreeNode *temp = root->right;
root->right = root->left;
root->left = NULL; //here i got the same problem
while(root->right){
root = root->right;
}
root->right = temp;
}

• I met the same question and solved, I forgot to set temp->left=nullptr

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