Flatten Binary Tree to Linked List: Runtime Error


  • 1
    M

    Can anyone help me to fix my code? I got a runtime error at following case, thanks!
    " Last executed input: {1,#,2}"

       class Solution {
        public:
            void flatten(TreeNode *root) {
                // IMPORTANT: Please reset any member data you declared, as
                // the same Solution instance will be reused for each test case.
                if(root==NULL)
                    return;
                TreeNode *p=NULL;
                stack<TreeNode *> st;
                st.push(root);
                while(st.empty()==false){
                    p=st.top();
                    st.pop();
                    if(p->left==NULL && p->right==NULL){
                        if(!st.empty())
                            p->right=st.top();
                    }else{
                        if(p->right!=NULL)
                            st.push(p->right);
                        if(p->left!=NULL){
                            st.push(p->left);
                            p->right=p->left;
                        }
                    }
                }
                return;
            }
        };

  • 6
    P

    Missing one line.

    class Solution {
    public:
        void flatten(TreeNode *root) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            if(root==NULL)
                return;
            TreeNode *p=NULL;
            stack<TreeNode *> st;
            st.push(root);
            while(st.empty()==false){
                p=st.top();
                st.pop();
                if(p->left==NULL && p->right==NULL){
                    if(!st.empty())
                        p->right=st.top(); 
                }else{
                    if(p->right!=NULL)
                        st.push(p->right);
                    if(p->left!=NULL){
                        st.push(p->left);
                        p->right=p->left;
                        p->left = NULL; // This is the only thing missing
                    }
                }
            }
            return;
        }
    };
    

  • 0
    M

    Good catch! Thanks!


Log in to reply
 

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