但是這個方法挪用了舊的樹,也就是root1,題目想要我們merge them into a new binary tree
classSolution{publicTreeNodemergeTrees(TreeNode root1,TreeNode root2){if(root1 ==null)return root2;if(root2 ==null)return root1;// Sum up the current nodes
root1.val += root2.val;// Build the left and right nodes
root1.left =mergeTrees(root1.left, root2.left);
root1.right =mergeTrees(root1.right, root2.right);return root1;}}
建立新的樹
classSolution{publicTreeNodemergeTrees(TreeNode root1,TreeNode root2){if(root1 ==null&& root2 ==null)returnnull;// In case a null node presentint val1 = root1 !=null? root1.val :0;int val2 = root2 !=null? root2.val :0;// Build the new treeTreeNode res =newTreeNode(val1 + val2);
res.left =mergeTrees(root1 !=null? root1.left :null, root2 !=null? root2.left :null);
res.right =mergeTrees(root1 !=null? root1.right :null, root2 !=null? root2.right :null);return res;}}