straight forward JAVA O(n) Solution


  • 0

    class Solution {
    public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
    return build(t1, t2);
    }

    public TreeNode build(TreeNode t1, TreeNode t2) {
        TreeNode t3 = new TreeNode(-1);
        // corner cases:
        if (t1 == null && t2 == null) {
            return null;
        } else if (t1 == null && t2 != null) {
            t3.val = t2.val;
            t3.left = build(null, t2.left);
            t3.right = build(null, t2.right);
    
        } else if (t1 != null && t2 == null) {
            t3.val = t1.val;
            t3.left = build(t1.left, null);
            t3.right = build(t1.right, null);
        } else {
            t3.val = t2.val + t1.val;
            t3.left = build(t1.left, t2.left);
            t3.right = build(t1.right, t2.right);
            
        }
        return t3;
    }
    

    }


Log in to reply
 

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