Elegant (imo) recursive Javascript solution


  • 0
    D
    var mergeTrees = function(t1, t2) {
        if (!t1 && !t2) {
            return null;
        }
        
       var sum = 0;
      
       sum = t1 ? sum + t1.val : sum;
       sum = t2 ? sum + t2.val : sum;
       
       var newNode = new TreeNode(sum);
       
       newNode.left = mergeTrees(t1 ? t1.left : null, t2 ? t2.left : null);
       newNode.right = mergeTrees(t1 ? t1.right : null, t2 ? t2.right : null);
       
       return newNode;
    };
    

Log in to reply
 

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