-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathMergeTwoBinaryTrees.cpp
More file actions
36 lines (32 loc) · 960 Bytes
/
Copy pathMergeTwoBinaryTrees.cpp
File metadata and controls
36 lines (32 loc) · 960 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
35
36
// Recursive Solution
/**
* 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)
{
if (t1 == NULL)
return t2;
if (t2 == NULL)
return t1;
t1->val += t2->val;
t1->left = mergeTrees(t1->left, t2->left);
t1->right = mergeTrees(t1->right, t2->right);
return t1;
}
};
// Time Complexity - O(m) -> m represents
// minimum no. of nodes that need to be traversed
// Space Complexity - O(m) -> depth of recursion tree
// can go upto m in case of a skewed tree
// while the average space complexity is O(logm)