-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmerge-two-binary-trees.cpp
More file actions
34 lines (29 loc) · 892 Bytes
/
Copy pathmerge-two-binary-trees.cpp
File metadata and controls
34 lines (29 loc) · 892 Bytes
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
28
29
30
31
32
33
34
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
//add the values of t2 onto t1
if(t1==NULL){
return t2;
}else if(t2==NULL){
return t1;
}else{
//t1!=NULL && t2!=NULL
//use t1 as final result
t1->val += t2->val;
t1->left = mergeTrees(t1->left, t2->left);
t1->right = mergeTrees(t1->right, t2->right);
return t1;
}
}
};