LeetCode 617.. 合并二叉树
原题链接
简单
作者:
owonder
,
2020-09-07 12:16:46
,
所有人可见
,
阅读 531
C++ 代码
/**
* 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* t1, TreeNode* t2) {
if(!t1&&!t2){
return nullptr;
}
if(!t1) return t2;
if(!t2) return t1;
TreeNode* root=new TreeNode(t1->val+t2->val);
root->left=mergeTrees( t1->left, t2->left);
root->right=mergeTrees( t1->right, t2->right);
return root;
}
};