题目:
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.
将两棵树合并,只需要顺序访问就行了。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void merge(TreeNode* t1, TreeNode* t2, TreeNode* &root)
{
if(!t1 and !t2)return;
if(t1 != nullptr and t2 != nullptr)
{
root = new TreeNode(t1->val + t2->val);
merge(t1->left, t2->left, root->left);
merge(t1->right, t2->right, root->right);
}
else if(t1)
{
root = new TreeNode(t1->val);
merge(t1->left, t2, root->left);
merge(t1->right, t2, root->right);
}
else
{
root = new TreeNode(t2->val);
merge(t1, t2->left, root->left);
merge(t1, t2->right, root->right);
}
}
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
TreeNode *root = nullptr;
merge(t1, t2, root);
return root;
}
};