617. 合并二叉树(c++)
程序员文章站
2022-03-03 10:36:17
...
暴力解,当t1为空返回t2,当t2为空返回t1。当t1,t2都有值,new新节点为两个节点的和,新节点左子树为原始节点左子树合并,新节点右子树为原始节点右子树合并。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
if (t1 == NULL)
{
return t2;
}
if (t2 == NULL)
{
return t1;
}
TreeNode* newnode = new TreeNode(t1->val + t2->val);
newnode->left = mergeTrees(t1->left, t2->left);
newnode->right = mergeTrees(t1->right, t2->right);
return newnode;
}
};
上一篇: Pycharm回退操作+常用批量操作
下一篇: 110 平衡二叉树