链接https://leetcode-cn.com/problems/merge-two-binary-trees/
解题代码
/**
* 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) {
if(root1==NULL && root2==NULL){//两棵树都为空树
return NULL;
}else if(root1==NULL && root2!=NULL){
root1 = root2;//把第二棵树的多出部分直接赋值给第一棵树
}else if(root1!=NULL && root2!=NULL){
root1->val += root2->val;//合并根节点
if(root1->left==NULL){
root1->left = root2->left;
}else{
mergeTrees(root1->left, root2->left);//合并左子树
}
if(root1->right==NULL){
root1->right = root2->right;
}else{
mergeTrees(root1->right, root2->right);//合并左子树
}
}
return root1;
}
};
运行结果