Why this solution caused RE while works on my Linux machine...


  • 1
    L

    Just simple preorder traversal and works well on my own machine, but caused RE here...The last executed input is {1,#,2}. Anyone any idea?

    /**
     * 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) {
            stack<TreeNode*> st;
            TreeNode* tmp;
            if(!root) return;
            st.push(root);
            while(!st.empty())
            {   
                tmp=st.top();
                st.pop();
                if(tmp->right)
                    st.push(tmp->right);
                if(tmp->left)
                    st.push(tmp->left);
                if(!st.empty())
                    tmp->right=st.top();
            }
        }
    };

  • 4
    A

    Your function works correctly but you don't clear up your left subtree.
    You should modify your code by adding just one line:

    class Solution {
    public:
        void flatten(TreeNode *root) {
            stack<TreeNode*> st;
            TreeNode* tmp;
            if(!root) return;
            st.push(root);
            while(!st.empty())
            {   
                tmp=st.top();
                st.pop();
                if(tmp->right)
                    st.push(tmp->right);
                if(tmp->left)
                    st.push(tmp->left);
                if(!st.empty())
                    tmp->right=st.top();
                    tmp->left = NULL;
            }
        }
    };
    

Log in to reply
 

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