题目描述
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.
Example 1:
Input:
Tree 1 Tree 2
1 2
/ \ / \
3 2 1 3
/ \ \
5 4 7
Output:
Merged tree:
3
/ \
4 5
/ \ \
5 4 7
Note: The merging process must start from the root nodes of both trees.
解决方案
/**
* 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* t;
if(NULL != t1 && NULL != t2){
t = new TreeNode(t1->val + t2->val);
}else if(NULL != t1){
t = new TreeNode(t1->val);
}else if(NULL != t2){
t = new TreeNode(t2->val);
}else{
return NULL;
}
return travel(t,t1,t2);
}
TreeNode* travel(TreeNode* t, TreeNode* t1, TreeNode* t2){
if(NULL != t1 && NULL != t2 && NULL != t1->left && NULL != t2->left){
t->left = new TreeNode(t1->left->val + t2->left->val);
travel(t->left, t1->left, t2->left);
}else if(NULL != t1 && NULL != t1->left){
t->left = t1->left;
}else if(NULL != t2 && NULL != t2->left){
t->left = t2->left;
}else{
t->left = NULL;
}
if(NULL != t1 && NULL != t2 && NULL != t1->right && NULL != t2->right){
t->right = new TreeNode(t1->right->val + t2->right->val);
travel(t->right, t1->right, t2->right);
}else if(NULL != t1 && NULL != t1->right){
t->right = t1->right;
}else if(NULL != t2 && NULL != t2->right){
t->right = t2->right;
}else{
t->right = NULL;
}
return t;
}
};
解题思路
遍历二叉树的思想,从根节点开始,同时递归遍历两棵二叉树,遍历过程中合并两棵二叉树。注意空节点的判断。
Submission Details
183 / 183 test cases passed.
Status: Accepted
Runtime: 49 ms
解决方案-改良
/**
* 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* t;
if(t1 && t2){
t = new TreeNode(t1->val + t2->val);
t->left = mergeTrees(t1->left, t2->left);
t->right = mergeTrees(t1->right, t2->right);
return t;
}else {
return t1 ? t1 : t2;
}
}
};
Submission Details
183 / 183 test cases passed.
Status: Accepted
Runtime: 39 ms
beats 91.78 % of cpp submissions
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。