题目:
Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.
You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree.
Example 1:
Input:
Tree 1 Tree 2
1 2
/ \ / \
3 2 1 3
/ \ \
5 4 7
Output:
Merged tree:
3
/ \
4 5
/ \ \
5 4 7
Note:
The merging process must start from the root nodes of both trees.
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
if(t1 == null && t2 == null) return null;
TreeNode newtree = new TreeNode(0);
recur(t1, t2, newtree);
return newtree;
}
public void recur(TreeNode t1, TreeNode t2, TreeNode newtree) {
//if(t1 == null && t2 == null) return;
// Calculate new node value
int t1val = (t1!=null)?t1.val:0;
int t2val = (t2!=null)?t2.val:0;
newtree.val = t1val + t2val;
// Go left
TreeNode t1left = null, t1right = null, t2left = null, t2right = null;
t1left = (t1 == null)? null:t1.left;
t2left = (t2 == null)? null:t2.left;
t1right = (t1 == null)? null:t1.right;
t2right = (t2 == null)? null:t2.right;
if(t1left != null || t2left != null) {
newtree.left = new TreeNode(0);
recur(t1left, t2left, newtree.left);
}
// Go right
if(t1right != null || t2right != null) {
newtree.right = new TreeNode(0);
recur(t1right, t2right, newtree.right);
}
}
精简后的代码
class Solution {
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
if(t1 == null && t2 == null) return null;
int sum = ((t1 == null)? 0:t1.val) + ((t2 == null)? 0:t2.val);
TreeNode newtree = new TreeNode(sum);
newtree.left = mergeTrees((t1 == null)? t1:t1.left, (t2 == null)? t2:t2.left);
newtree.right = mergeTrees((t1 == null)? t1:t1.right, (t2 == null)? t2:t2.right);
return newtree;
}
}