C++ in-place solution (no additional node was created)


  • 0
    G
    class Solution {
    public:
        TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
            if(t1 == nullptr && t2 == nullptr){
            	return nullptr;
            }
            
            if(t1 != nullptr && t2 != nullptr){
            	t1->val += t2->val;
            }
            
            (t1 ? t1->left : t2->left ) = mergeTrees((t1 ? t1->left : nullptr), (t2 ? t2->left : nullptr));
            (t1 ? t1->right : t2->right) = mergeTrees((t1 ? t1->right : nullptr), (t2 ? t2->right : nullptr));
            
            return t1 ? t1 : t2;
        }
    };
    

Log in to reply
 

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