6-liner C++ and Python recursive solution


  • 0

    C++

        TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
          if (t1 && t2) {
            auto t   = new TreeNode(t1->val + t2->val);
            t->left  = mergeTrees(t1->left,  t2->left);
            t->right = mergeTrees(t1->right, t2->right);
            return t;  
          }    
          return t1? t1 : t2;
        }
    

    Python

        def mergeTrees(self, t1, t2):
            if (t1 and t2) :
                t = TreeNode(t1.val+t2.val)
                t.left  = self.mergeTrees(t1.left,  t2.left)
                t.right = self.mergeTrees(t1.right, t2.right)
                return t
            return t1 or t2
    

Log in to reply
 

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