8ms C++ solution


  • 0
    P
    class Solution {
        
    TreeNode* do_flatten(TreeNode* node) {
        if (node == NULL) {
            return NULL;
        }
    
        TreeNode* left = node->left;
        node->left = NULL;
        TreeNode* right = node->right;
    
        if(left == NULL && right == NULL){
            return node;
        }
        else if(left ==NULL){
            return do_flatten(right);
        }
        else if(right == NULL){
            node->right = left;
            return do_flatten(left);
        }
        else{
            node->right = left;
            TreeNode* leftLast = do_flatten(left);
            TreeNode* rightLast = do_flatten(right);
            leftLast->right = right;
            return rightLast;
        }
    }
    
    
    public:
        void flatten(TreeNode* root) {
            do_flatten(root);
        }
    };

Log in to reply
 

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