Welcome to LeetCode Discuss.  Please read the FAQ to help yourself making the best use of Discuss.
Ask a Question
Back to Problem

Welcome to LeetCode Discuss.

This is a place to ask questions related to only OJ problems.

Please read the FAQ to help yourself making the best use of Discuss.

Flatten Binary Tree to Linked List: Runtime Error

+1 vote
232 views

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;
        }
    };
asked Nov 21, 2013 in Flatten Binary Tree to Linked List by MagicPowder (130 points)

1 Answer

+4 votes

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;
    }
};
answered Nov 21, 2013 by porker2008 (7,150 points)

Good catch! Thanks!


...