My C++ Solution, 6ms


  • 0
    W
    class Solution {
    public:
        void flatten(TreeNode* root) {
            helper(root);
        }
        //return tail pointer
        TreeNode* helper(TreeNode* root){
            if(root == nullptr) return nullptr;
            TreeNode* temp = root;
            while(temp){
                if(temp->left){
                    TreeNode* q = temp->left;
                    temp->left = nullptr;
                    TreeNode* tail = helper(q);
                    if(tail){
                        tail->right = temp->right;
                        temp->right = q;
                    }
                }
                temp = temp->right;
            }
            TreeNode* p = root;
            while(p->right)
                p = p->right;
            return p;
        }
    };
    

Log in to reply
 

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