采用递归的方式合并,有两种方式:
第一种方式是将两棵树合并到t1中,如果t1和t2对应位置都有节点,就将t2结点的值加到t1节点的值上,若t1对应位置没有节点,而t2有节点,就将t2在该位置的节点复制到t1中,若t2在该位置没有节点,也就只需要对t1进行处理,由于最终都是合并在t1上,所以这种情况可以不用进行处理。
第二种方式是新建一棵新的二叉树,每一个节点都是新节点,新节点的值就是t1和t2中对应节点的值之和。
合并到t1中的代码:
class Solution {
public:
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
if(t1 && t2){
t1->val += t2->val;
t1->left = mergeTrees(t1->left, t2->left);
t1->right = mergeTrees(t1->right, t2->right);
}else if(t2){
t1 = t2;
t1->left = mergeTrees(NULL, t2->left);
t1->right = mergeTrees(NULL, t2->right);
}
//t1不空t2空、t1和t2都空的情况不用再另外处理,就相当于只有t1
return t1;
}
};
创建一棵新的二叉树代码:
class Solution {
public:
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
int tmp;
TreeNode* root;
if(t1 && t2){
tmp = t1->val + t2->val;
root = new TreeNode(tmp);
root->left = mergeTrees(t1->left, t2->left);
root->right = mergeTrees(t1->right, t2->right);
}else if(t1){
tmp = t1->val;
root = new TreeNode(tmp);
root->left = mergeTrees(t1->left, NULL);
root->right = mergeTrees(t1->right, NULL);
}else if(t2){
tmp = t2->val;
root = new TreeNode(tmp);
root->left = mergeTrees(NULL, t2->left);
root->right = mergeTrees(NULL, t2->right);
} else {
root = NULL;
}
return root;
}
};
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)