1. Title
2. Ideas (description in Java language)
Take the t1 node as the root node, modify the pointer in place and
return the exit condition recursively
- If one of the nodes is not empty, return the non-empty node
- Modify the pointer on the original tree of t1
- Both are empty, return t1 directly
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
if(t1!=null&&t2!=null){
t1.val+=t2.val;
mergeTrees(t1.left,t2.left);
mergeTrees(t1.right,t2.right);
if(t1.left == null&&t2.left!=null){
t1.left = t2.left;
}
if(t1.right==null&&t2.right!=null){
t1.right=t2.right;
}
return t1;
}
if(t1==null&&t2!=null){
return t2;
}
if(t1!=null&&t2==null){
return t1;
}
return t1;
}
}
Time complexity T(N), space complexity O(1)