c++ 3ms easy understand recursive solution


  • 0
    F
    class Solution {
    public:
        TreeNode* flattenHelper(TreeNode *root){
            if(root->left == NULL and root->right == NULL){
                return root;
            }
            else if(root->left == NULL and root->right != NULL){
                return flattenHelper(root->right);
            }else if(root->left != NULL and root->right == NULL){
                root->right = root->left;
                root->left = NULL;
                return flattenHelper(root->right);
            }else{
                TreeNode * leftLast = flattenHelper(root->left);
                TreeNode * rightLast = flattenHelper(root->right);
                TreeNode * rightFirst = root->right;
                root->right = root->left;
                leftLast->right = rightFirst;
                root->left = NULL;
                return rightLast;
            }
        }
        void flatten(TreeNode* root) {
            if(root == NULL)    return;
            else    flattenHelper(root);
        }
    };
    

Log in to reply
 

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