-
Notifications
You must be signed in to change notification settings - Fork 0
/
617. Merge Two Binary Trees
38 lines (35 loc) · 1.05 KB
/
617. Merge Two Binary 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
28
29
30
31
32
33
34
35
36
37
38
/**
* 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;
}
int val = 0;
TreeNode* root = new TreeNode(0);
if(t1 != NULL && t2!= NULL){
val = t1->val+t2->val;
root->val = val;
root->left = mergeTrees(t1->left,t2->left);
root->right = mergeTrees(t1->right,t2->right);
}else if(t1 != NULL){
root->val = t1->val;
root->left = mergeTrees(t1->left,NULL);
root->right = mergeTrees(t1->right,NULL);
}else if(t2!= NULL){
root->val = t2->val;
root->left = mergeTrees(NULL,t2->left);
root->right = mergeTrees(NULL,t2->right);
}
// cout << root->val << endl;
return root;
}
};