File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed
18 - Binary Search Tree Data Structure Problems/17 - Merge Two BST's Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public:
3+ void inOrder (Node* root, vector<int > &bst){
4+ if (root == NULL ) return ;
5+
6+ inOrder (root -> left, bst);
7+ bst.push_back (root -> data);
8+ inOrder (root -> right, bst);
9+ }
10+
11+ vector<int > merge (Node *root1, Node *root2) {
12+ vector<int > bst1, bst2;
13+
14+ inOrder (root1, bst1);
15+ inOrder (root2, bst2);
16+
17+ vector<int > merged;
18+
19+ int i = 0 ;
20+ int j = 0 ;
21+ while (i < bst1.size () && j < bst2.size ()){
22+ if (bst1[i] < bst2[j]){
23+ merged.push_back (bst1[i++]);
24+ }else {
25+ merged.push_back (bst2[j++]);
26+ }
27+ }
28+
29+ while (i < bst1.size ()){
30+ merged.push_back (bst1[i++]);
31+ }
32+
33+ while (j < bst2.size ()){
34+ merged.push_back (bst2[j++]);
35+ }
36+
37+ return merged;
38+ }
39+ };
You can’t perform that action at this time.
0 commit comments