Merge Two Balanced Binary Search Trees
#include<bits/stdc++.h>
using namespace std;
#define shailesh ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define int long long int
#define vi vector<int>
#define pii pair<int, int>
#define vii vector<pii>
#define rep(i, a, b) for(int i=a; i<b; i++)
#define ff first
#define ss second
const int N=1e5+10;
bool isPowerOfTwo(int x){
return x&&(!(x&(x-1)));
}
bool isPrime(int n)
{
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
bool isPalindrome(string S)
{
for (int i = 0; i < S.length() / 2; i++) {
if (S[i] != S[S.length() - i - 1]) {
return false;
}
}
return true;
}
vector<int> v1;
vector<int> v2;
vector<int> v3;
struct Node{
int data;
struct Node* left;
struct Node* right;
Node(int val){
data=val;
left=NULL;
right=NULL;
}
};
void inorder(Node* root1){
if(!root1) return;
inorder(root1->left);
v1.push_back(root1->data);
inorder(root1->right);
}
void inorder1(Node* root2){
if(!root2) return;
inorder1(root2->left);
v2.push_back(root2->data);
inorder1(root2->right);
}
Node* vectortobst(vector<int> &v3, int start, int end){
if(start>end){
return NULL;
}
int mid=(start+end)/2;
Node* root=new Node(v3[mid]);
root->left=vectortobst(v3, start, mid-1);
root->right=vectortobst(v3, mid+1, end);
return root;
}
void preOrder(Node* node)
{
if (node == NULL)
return;
preOrder(node->left);
cout << node->data << " ";
preOrder(node->right);
}
signed main(){
shailesh
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
struct Node* root1=new Node(100);
root1->left=new Node(50);
root1->left->left=new Node(20);
root1->left->right=new Node(70);
root1->right=new Node(300);
struct Node* root2=new Node(80);
root2->left=new Node(40);
root2->right=new Node(120);
inorder(root1);
inorder1(root2);
for(int i=0; i<v1.size(); i++){
v3.push_back(v1[i]);
}
for(int i=0; i<v2.size(); i++){
v3.push_back(v2[i]);
}
sort(v3.begin(), v3.end());
int n=v3.size();
Node *root = vectortobst(v3, 0, n-1);
preOrder(root);
return 0;
}
Comments
Post a Comment