GeeksforGeeks » Trees specific questions
Merge two BSTs
(5 posts)-
Problem: Merge two BSTs .
#include<iostream> class node{ public: int d; node* l; node* r; node(int x):d(x),l(0),r(0){} }; void add(int x,node *&a){//lower or equal value to the left BST if(!a)a=new node(x); else if(x>a->d)add(x,a->r); else add(x,a->l); } void print(node *a){ if(a){ print(a->l); std::cout<<a->d<<" "; print(a->r); } } void merge(node *&a,node *&b){//merge b into a if(b==0)return; else if(a==0)a=b; else if(a->d<b->d){ node* t = b->l; b->l=0; merge(a,t); merge(a->r,b); } else if(a->d>=b->d){ node *t = b->r; b->r=0; merge(a->l,b); merge(a,t); } } int main(){ #define NL std::cout<<"\n" node *a=0, *b=0; add(8,a);add(3,a);add(1,a);add(6,a);add(4,a); add(7,a);add(10,a);add(14,a);add(13,a); add(8,b);add(3,b);add(1,b);add(6,b);add(4,b); add(7,b); print(a);NL; print(b);NL; merge(a,b); b=0; print(a); return 0; } -
#include "stdafx.h" #include "stdlib.h" #include "stdio.h" struct node{ int d; struct node* l; struct node* r; }; struct node *createNode(int x) { struct node * pTemp =(struct node *) malloc(sizeof(struct node)); pTemp->d =x;pTemp->l=NULL; pTemp->r = NULL; return pTemp; } void insert(struct node *pIns,struct node **pRoot){ if (!(*pRoot)) { *pRoot = pIns; return;} struct node *pTemp = *pRoot; struct node *pParent = NULL; while (pTemp) { if (pIns->d < pTemp->d) { pParent = pTemp; pTemp = pTemp->l; continue; } else { pParent = pTemp; pTemp = pTemp->r; continue; }; } if (pIns->d <pParent->d) pParent->l = pIns; else pParent->r = pIns; } void merge(struct node **aa,struct node *b){//merge b into a struct node *a=*aa; if(b==0)return; else if(a==0)a=b; else if ((b->l == NULL)&&(b->r == NULL)) insert(b, &a); else if(a->d < b->d){ struct node* t = b->l; b->l=NULL; merge(&a,t); merge(&a->r,b); } else if(a->d >= b->d){ struct node *t = b->r; b->r=NULL; merge(&a->l,b); merge(&a,t); } *aa=a; } int main(){ struct node *pRoot= NULL; struct node *pRoot1=NULL; insert(createNode(3),&pRoot1); insert(createNode(8),&pRoot1); // insert(createNode(4),&pRoot1); insert(createNode(1),&pRoot1); //insert(createNode(6),&pRoot1); insert(createNode(5),&pRoot); insert(createNode(9),&pRoot); // insert(createNode(7),&pRoot); insert(createNode(2),&pRoot); // insert(createNode(10),&pRoot); merge(&pRoot, pRoot1); return 0; } -
this has a simple solution.
Find the preorder traversal of both lists , this gives the list in ascending order.
Copy it in an array and then call BST with the array
Running time
O(n) + O(m) + c(m+n) + O(m+n)
where n- no of elements in tree 1
m= no of elements in tree2
c- constant time to copy each element to an array
O(m+n) - time for BST algo to construct a BST -
Hi, I registered on a dating site, http://pinadating.com, it's better than a site http://dating.com, I need a girl, I want to find love!
-
Check this solution
http://dzmitryhuba.blogspot.com/2011/03/merge-binary-search-trees-in-place.html
Reply
You must log in to post.