Saved Bookmarks
| 1. |
Write a function to merge two sorted binary search tree |
|
Answer» Input: First BST 7 / \ 5 9 Second BST 4 / \ 3 12 Output: 3 4 5 6 7 9 12 //Function to return a list of integers denoting the node//values of both the BST in a sorted order. void inorder(Node*root,vector<int>&v){ if(root==NULL) return; inorder(root->left,v); v.push_back(root->data); inorder(root->right,v); } vector<int> merge(vector<int>v1,vector<int>v2){ vector<int>v; int n1=v1.size(),n2=v2.size(),i=0,j=0; while(i<n1&&j<n2){ if(v1[i]>v2[j]){ v.push_back(v2[j]); j++; } else{ v.push_back(v1[i]); i++; } } while(i<n1){ v.push_back(v1[i]); i++; } while(j<n2){ v.push_back(v2[j]); j++; } return v; } vector<int> merge(Node *root1, Node *root2) { vector<int>v1,v2; inorder(root1,v1); inorder(root2,v2); return merge(v1,v2); }
|
|