Leetcode 617. Merge Two Binary Trees
Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree.
题目大意:
给定两棵二叉树将其合并成一棵,规则是如果两棵树的节点均存在,则合并后为两棵数该处节点之和,如果其中一颗树节点存在而另一棵不存在,则合并后为存在的那棵树的该处节点的值,如果都不存在则为空。
解题思路:
采用递归的方法,如果两棵树该节点都存在,则建立新的节点其值为两树该处值之和并递归该节点的左右子节点。如果只有一棵树该节点存在,则返回此值并递归该树的左右子节点。如果都不存在则返回空。
代码1:
/**
* 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) {
TreeNode *res = NULL;
helper(t1, t2, res);
return res;
}
void helper(TreeNode *t1, TreeNode* t2, TreeNode* &res){
if(!t1 && !t2)
return;
else if(t1 && !t2)
{
res = new TreeNode(t1->val);
helper(t1->left, NULL, res->left);
helper(t1->right, NULL, res->right);
}
else if(!t1 && t2)
{
res = new TreeNode(t2->val);
helper(NULL, t2->left, res->left);
helper(NULL, t2->right, res->right);
}
else
{
res = new TreeNode(t1->val + t2->val);
helper(t1->left, t2->left, res->left);
helper(t1->right, t2->right, res->right);
}
}
};
代码2 (精简):
class Solution {
public:
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
if(!t1) return t2;
if(!t2) return t1;
TreeNode *t = new TreeNode(t1->val + t2->val);
t->left = mergeTrees(t1->left, t2->left);
t->right = mergeTrees(t1->right, t2->right);
return t;
}
};