-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMerge_two_BST.cpp
79 lines (68 loc) · 1.52 KB
/
Merge_two_BST.cpp
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*
Problem Statement:
-----------------
Given two BSTs, return elements of both BSTs in sorted form.
Example 1:
---------
Input:
BST1:
5
/ \
3 6
/ \
2 4
BST2:
2
/ \
1 3
\
7
/
6
Output: 1 2 2 3 3 4 5 6 6 7
Explanation: After merging and sorting the two BST we get 1 2 2 3 3 4 5 6 6 7.
Example 2:
---------
Input:
BST1:
12
/
9
/ \
6 11
BST2:
8
/ \
5 10
/
2
Output: 2 5 6 8 9 10 11 12
Explanation: After merging and sorting the two BST we get 2 5 6 8 9 10 11 12.
Your Task: You don't need to read input or print anything. Your task is to complete the function merge() which takes roots of both the BSTs
as its input and returns an array of integers denoting the node values of both the BSTs in a sorted order.
Expected Time Complexity: O(M+N) where M and N are the sizes if the two BSTs.
Expected Auxiliary Space: O(Height of BST1 + Height of BST2).
*/
// Link --> https://practice.geeksforgeeks.org/problems/merge-two-bst-s/1#
// Code:
class Solution
{
public:
vector<int> answer;
void inorder(Node *root)
{
if(root == NULL)
return;
answer.push_back(root->data);
inorder(root->left);
inorder(root->right);
}
vector<int> merge(Node *root1 , Node *root2)
{
answer.clear();
inorder(root1);
inorder(root2);
sort(answer.begin() , answer.end());
return answer;
}
};