Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

Merge Two Binary Trees

// 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;
};
Source by dev.to #
 
PREVIOUS NEXT
Tagged: #Merge #Two #Binary #Trees
ADD COMMENT
Topic
Name
7+9 =