[LeetCode]617. Merge Two Binary Trees

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.

Example 1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Input: 
trueTree 1 Tree 2
1 2
/ \ / \
3 2 1 3
/ \ \
5 4 7
Output:
Merged tree:
true 3
true / \
true 4 5
true / \ \
true 5 4 7

Note: The merging process must start from the root nodes of both trees.

题目解释:合并两棵数,对应节点的值相加,其中一个为空的话,就留一个节点的数值;

方法一

思路:左右两棵树分别递归合并,判断左子树和右子树合法性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* 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 && t2 == NULL) {
return NULL;
}
if (t1 == NULL && t2 != NULL){
return t2;
}
if (t1 != NULL && t2 == NULL){
return t1;
}
t1->val += t2->val;
t1->left = mergeTrees(t1->left, t2->left);
t1->right = mergeTrees(t1->right, t2->right);
return t1;
}
};

result

Runtime: 56 ms, faster than 12.37% of C++ online submissions for Merge Two Binary Trees.

Memory Usage: 13.9 MB, less than 72.49% of C++ online submissions for Merge Two Binary Trees.

方法二

上一个方法效率有点差,想了想,改了一下if语句的判断,效果提升明显。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* 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 && t2 == NULL) {
return NULL;
} else if (t1 == NULL && t2 != NULL){
return t2;
} else if (t1 != NULL && t2 == NULL){
return t1;
}
t1->val += t2->val;
t1->left = mergeTrees(t1->left, t2->left);
t1->right = mergeTrees(t1->right, t2->right);
return t1;
}
};

result

Runtime: 32 ms, faster than 99.18% of C++ online submissions for Merge Two Binary Trees.

Memory Usage: 13.7 MB, less than 76.34% of C++ online submissions for Merge Two Binary Trees