Why in the case {1,#,2},it returns a run time error, however it's ok in VS2010


  • 3
    T
    TreeNode* flat(TreeNode *root){
            //case {1,#,2}
            if(root==NULL)
                return root;
            else if(root->left!=NULL){
                TreeNode* tmp=root->right;
                root->right=root->left;
                flat(root->left)->right=tmp;
                return flat(tmp);
            }
            else if(root->right!=NULL){
                TreeNode* ret=flat(root->right);
                return ret;
            }
            else
                return root;
        }
        void flatten(TreeNode *root) {
            TreeNode* tail=flat(root);
        }

  • 9
    S

    You have to make sure the result is a tree * that has does not contain any left child *, as shown in the example. Your code correctly builds the links on the right hand side, and therefore when you traverse only on the right side, it would produce the correct sequence. However, it does not remove the links to left children. So the final result does not fit the expectation. You should add a "root->left = NULL" somewhere in your code.


  • 0
    T

    You are right. Also I forget to think about the case that the right child is originally null. It's working now, thanks.


  • 0
    B

    agreed~~~the same wrong happened to me


  • 0
    H

    thanks a lot. It's really help !


  • 0
    Z

    But according to this case {1,#,2}, the left child should be null. oj also think the left child is not null?


  • 0
    S
    This post is deleted!

  • 0
    D

    Appreciate it!


Log in to reply
 

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