#include #include struct stablo{ int x; struct stablo *levi,*desni; }; struct stablo *nadji(struct stablo *koren,int k){ if(!koren) return NULL; if(koren->x == k) return koren; struct stablo *pom=nadji(koren->levi,k); if(pom) return pom; pom=nadji(koren->desni,k); return pom; } void dodaj(struct stablo *koren,int k, int l, int d){ struct stablo *pom = nadji(koren,k); pom->levi = (struct stablo *)malloc(sizeof(struct stablo)); pom->desni = (struct stablo *)malloc(sizeof(struct stablo)); pom->levi->levi = pom->levi->desni = pom->desni->levi = pom->desni->desni = NULL; if(l){ pom->levi->x = l; } else { pom->levi = NULL; } if(d){ pom->desni->x = d; } else { pom->desni = NULL; } } struct stablo *ucitaj(){ struct stablo *koren = (struct stablo *)malloc(sizeof(struct stablo)); int k,l,d; scanf("%d",&k); koren->x = k; koren->levi = koren->desni = NULL; while(1){ scanf("%d",&k); if(!k) break; scanf("%d%d",&l,&d); dodaj(koren,k,l,d); } return koren; } int uStablu(struct stablo *koren, int k){ if(!koren) return 0; if(koren->x == k) return 1; int n = uStablu(koren->levi,k); if(n) return 1; n = uStablu(koren->desni,k); return n; } void put(struct stablo *koren, int *a, int *n, int k){ if(uStablu(koren->levi,k)){ a[(*n)++]=koren->levi->x; put(koren->levi,a,n,k); } if(uStablu(koren->desni,k)){ a[(*n)++]=koren->desni->x; put(koren->desni,a,n,k); } } void ispis(struct stablo *koren){ if(!koren) return; ispis(koren->levi); printf("%d ",koren->x); ispis(koren->desni); } int main(){ struct stablo *koren = ucitaj(); ispis(koren); int m; scanf("%d",&m); for(int i = 0; i < m;i++){ int p,q; scanf("%d%d",&p,&q); if(uStablu(koren,p) && uStablu(koren,q)){ int a[100],b[100]; int n1=1,n2=1; a[0] = koren->x; b[0] = koren->x; put(koren,a,&n1,p); put(koren,b,&n2,q); if(n1 < n2){ for(int j=0;j