Java solution reusing not null nodes


  • 0
    I

    The premise of this solution is the following line in the question:

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

    This could be interpreted differently, but the interpretation I am using is that we will use the same node (not node value) as the node for the new tree.

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
            if (t1 == null || t2 == null) {
                if (t1 == null) {
                    return t2;
                }
                return t1;
            }
            
            TreeNode mergedTree = new TreeNode(t1.val + t2.val);
            mergedTree.left = mergeTrees(t1.left, t2.left);
            mergedTree.right = mergeTrees(t1.right, t2.right);
            
            return mergedTree;
        }
    }
    

Log in to reply
 

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