Short Recursive Solution w/ Python & C++


  • 14
    Z

    python solution

    class Solution(object):
        def mergeTrees(self, t1, t2):
            if t1 and t2:
                root = TreeNode(t1.val + t2.val)
                root.left = self.mergeTrees(t1.left, t2.left)
                root.right = self.mergeTrees(t1.right, t2.right)
                return root
            else:
                return t1 or t2
    

    c++ solution

    class Solution {
    public:
        TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
            if ( t1 && t2 ) {
                TreeNode * root = new TreeNode(t1->val + t2->val);
                root->left = mergeTrees(t1->left, t2->left);
                root->right = mergeTrees(t1->right, t2->right);
                return root;
            } else {
                return t1 ? t1 : t2;
            }
        }
    };
    

  • 0
    Y

    @zqfan Don't think this is the safest solution, memory-management wise. By returning either t1 or t2 if the other is null, you're mixing newly allocated memory with existing allocated memory in the new tree - making it difficult to decipher what is safe to delete after the merge.


  • 0
    Z

    @YearlyBoar said in Short Recursive Solution w/ Python & C++:

    @zqfan Don't think this is the safest solution, memory-management wise. By returning either t1 or t2 if the other is null, you're mixing newly allocated memory with existing allocated memory in the new tree - making it difficult to decipher what is safe to delete after the merge.

    100% agree, but as the problem description says: Otherwise, the NOT null node will be used as the node of new tree. so here comes this solution.


  • 0
    S

    thanks for your solution!easy to understand


  • 0
    W

    The python code is clean and beautiful!


Log in to reply
 

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