HDU 1710 Binary Tree Traversals(二叉樹),hdutraversals

來源:互聯網
上載者:User

HDU 1710 Binary Tree Traversals(二叉樹),hdutraversals

題目地址:HDU 1710

已知二叉樹先序和中序求後序。

#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 解

#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), 不是1到9
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.