HDU 1710 Binary Tree Traversals (Binary Tree), hdutraversals
Address: HDU 1710
It is known that Binary Trees are sorted in ascending order and in descending order.
#include <stdio.h>#include <string.h>int a[1001], cnt;typedef struct node{ int date ; node *lchild , *rchild ;}*tree;int getk(int ch,int ino[],int is,int n){ for(int i = is ; i <= is + n -1 ; i++) if(ino[i]==ch)return i;}void gettree(tree &t,int pre[],int ino[],int ps,int is,int n){ if(n==0) t = NULL; else { t = new node; t->date = pre[ps]; int k = getk(pre[ps],ino,is,n); if(k == is) t->lchild = NULL; else gettree(t->lchild,pre,ino,ps+1,is,k-is); if(k == is+n-1) t->rchild = NULL; else gettree(t->rchild,pre,ino,ps+1+(k-is),k+1,n-1-(k-is)); }}void pritree1(tree t){ if(t) { pritree1(t->lchild); pritree1(t->rchild); a[cnt++]=t->date; }}int main(){ int i, n, t; int pre[1001] , ino[1001] ; while(scanf("%d", &n)!=EOF) { cnt=0; tree head; for(i=0; i<n; i++) { scanf("%d",&pre[i]); } for(i=0; i<n; i++) { scanf("%d",&ino[i]); } gettree(head,pre,ino,0,0,n); pritree1(head); for(i=0; i<cnt-1; i++) printf("%d ",a[i]); printf("%d\n",a[cnt-1]); } return 0;}
Hdu 1710 Binary Tree Traversals wrong answer Solution
# Include <stdio. h>
Void build (int n, int a [], int B [], int c [])
{
Int I;
Int p;
If (n <= 0)
{
Return;
}
P = a [0];
For (I = 0; I <n; I ++)
{
If (B [I] = p)
Break;
}
Build (I, a + 1, B, c );
Build (n-i-1, a + I + 1, B + I + 1, c + I );
C [n-1] = p;
}
Int main ()
{
Int a [1001], B [1001], c [1001];
Int m;
Int I;
While (scanf ("% d", & m )! = EOF)
{
For (I = 0; I <m; I ++)
{
Scanf ("% d", & a [I]);
}
For (I = 0; I <m; I ++)
{
Scanf ("% d", & B [I]);
}
Build (m, a, B, c );
For (I = 0; I <m-1; I ++)
{
Printf ("% d", c [I]);
}
Printf ("% d \ n", c [I]);
}
Return 0;
}
N (1 <= n <= 1000), not 1 to 9