617. Merge Two Binary Trees

cod3pineapple

codingpineapple

Posted on February 15, 2021

617. Merge Two Binary Trees

Description:

You are given two binary trees root1 and root2.

Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree.

Return the merged tree.

Note: The merging process must start from the root nodes of both trees.

Solution:

Time Complexity : O(n)
Space Complexity: O(n)

// Depth first search approach
// We will use t1 as the merged tree
var mergeTrees = function(t1, t2) {
    // If any of the nodes is null then use the other node as the merged node
    if (t1 === null)
        return t2;
    if (t2 === null)
        return t1;
    // Add the vals of current node for each step if they are not null
    t1.val += t2.val;
    // Explore remaining children in the trees
    t1.left = mergeTrees(t1.left, t2.left);
    t1.right = mergeTrees(t1.right, t2.right);
    return t1;
};
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
cod3pineapple
codingpineapple

Posted on February 15, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

617. Merge Two Binary Trees
algorithms 617. Merge Two Binary Trees

February 15, 2021