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);
}
}
};
Getting a runtime error on input {1,#,2}


/** * 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); } }
};