Explained Solution


  • 0
    N

    class Solution {
    public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
    TreeNode head;
    if(t1 != null && t2 != null){
    head = new TreeNode(t1.val+t2.val);
    head.left = mergeTrees(t1.left, t2.left);
    head.right = mergeTrees(t1.right, t2.right);
    } else if(t1 != null){
    head = t1;
    } else {
    head = t2;
    }
    return head;
    }
    }

    // if none from the two nodes is null then we add the two and then make recursive calls on left and right of both the nodes. Else we return the node which isn't null and are saved from adding nodes which are already added by simply not creating a new node but returning the same node as all the rest of the nodes which are not required to be added will be automatically added.


Log in to reply
 

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