问题抽象
合并两颗二叉树,重叠部分值相加
算法
直接实现即可,容易想到以某棵树为准,将另一颗树上的节点合并过去
复杂度
$O(N)$
代码
/**
* 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:
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
root1 = dfs(root1, root2);
return root1;
}
TreeNode* dfs(TreeNode* r1, TreeNode *r2){
if(!r1 && !r2) return nullptr;
if(!r1 && r2){
return r2;
}
if(r1 && r2){
r1 -> val += r2 -> val;
r1->left = dfs(r1->left, r2->left);
r1 -> right = dfs(r1->right, r2->right);
}
return r1;
}
};