Short Recursive Solution w/ Python & C++


  • 17
    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;
            }
        }
    };
    

  • 1
    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!


  • 0
    C

    Otherwise, the NOT null node will be used as the node of new tree.

    I think the meaning of the sentence is that the value of the non-null node should be used as value of node in new tree, the way you have done it makes the code easy but results in parts of the new tree pointing to parts of the old trees, just a concern


Log in to reply
 

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