clean c++ recursive solution using stack


  • 1
    H
    class Solution {
    public:
        void flatten(TreeNode* root) {
            if(!root) return;
            if(root->right) mystack.push(root->right);
            root->right = root->left;
            root->left = NULL;
            flatten(root->right);
            if(!mystack.empty()) {
                root->right = mystack.top();
                mystack.pop();
                flatten(root->right);
            }
        }
    private:
        stack<TreeNode* > mystack;
    };
    

  • 0
    A

    This section should be checked with if(root->left), otherwise it's costs performance for no reason.

            root->right = root->left;
            root->left = NULL;
            flatten(root->right);
    

Log in to reply
 

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