给出两棵二叉树,当你用其中一棵覆盖另一棵时,两棵树的一些节点会发生重叠,而其他节点则不会重叠。
您需要将它们合并到一棵新的二叉树中。 合并的规则是如果两个节点重叠,则将节点值加起来作为合并节点的新值。 否则,非空的节点将用作新树的节点。
样例
样例1
输入:
{1,3,2,5}
{2,1,3,#,4,#,7}
输出:
{3,4,5,5,4,#,7}
解释:
树 1 树 2
1 2
/ \ / \
3 2 1 3
/ \ \
5 4 7
合并的树:
3
/ \
4 5
/ \ \
5 4 7
样例2
输入:
{1}
{1,2}
输出:
{2,2}
注意事项
合并过程必须从两个树的根节点开始。
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param t1: the root of the first tree
* @param t2: the root of the second tree
* @return: the new binary tree after merge
*/
TreeNode * mergeTrees(TreeNode * t1, TreeNode * t2) {
// Write your code here
return creat(t1,t2);
}
TreeNode * creat(TreeNode * t1, TreeNode * t2)
{
if(t1 == NULL && t2 == NULL)
return NULL;
else if(t1 == NULL)
{
return t2;
}
else if(t2 == NULL)
{
return t1;
}
t1->val = t1->val + t2->val;
t1->left = creat(t1->left, t2->left);
t1->right = creat(t1->right, t2->right);
return t1;
}
};