Description
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:
Note
The merging process must start from the root nodes of both trees.
Coding
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
//合并算法:
//对应位置如果都存在,把两者相加的和放到t1节点上
//t1存在,t2不存在,什么也不需要操作,直接返回t1指针
//t2存在,t1不存在,什么也不需要操作,直接返回t2指针
//t1左(右)子树存在,t2左(右)子树不存在,把t2子树接到t1的左(右)子树上,结束本次操作
//t2左(右)子树存在,t1左(右)子树不存在,把t1子树接到t2的左(右)子树上,结束本次操作
class Solution {
public:
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
if (t1 && t2) {
t1->val = t1->val + t2->val;
if (t1->left) {
mergeTrees(t1->left, t2->left);
}else {
t1->left = t2->left;
}
if (t1->right) {
mergeTrees(t1->right, t2->right);
} else {
t1->right = t2->right;
}
} else {
if (t2) {
return t2;
} else {
return t1;
}
}
return t1;
}
};