14ms C++ recursive solution


  • 0
    X
    class Solution {
    private:
        // This would return the last node  
        TreeNode* flatTree(TreeNode *root) {
            if(!root->left && !root->right) return root;
            if(!root->right) {
                root->right = root->left;
                root->left = NULL;
                return flatTree(root->right);
            }
            if(!root->left) return flatTree(root->right);
            TreeNode* oldRight = root->right;
            root->right = root->left;
            (flatTree(root->right))->right = oldRight;
            root->left = NULL;
            return flatTree(root->right);
        }
    public:
        void flatten(TreeNode *root) {
            if(!root) return;
            flatTree(root);
        }
    };

Log in to reply
 

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