题目1078:二叉树遍历

来源:互联网 发布:法国大革命 评价 知乎 编辑:程序博客网 时间:2024/06/01 08:19

#include "iostream"#include "stdio.h"#include <vector>#include <cstring>#include <algorithm>#include <string>#include <string.h>#include <stack>using namespace std;//1078char pre[30],in[30];int cur,n; struct node{    node *l,*r;    char c;};int find(char c){    for(int i=0;in[i]!=0;i++){        if(c==in[i])            return i;    }}node* build(int l,int r){    if(l>r)  return NULL;    char root=pre[cur++];    int rootIdx=find(root);    node *T=(node*)malloc(sizeof(node));    T->c=root;    if(l==r)    T->r=T->l=NULL;    else{        T->l=build(l,rootIdx-1);        T->r=build(rootIdx+1,r);    }    return T;}void postOrder(node* T){    if(T->l) postOrder(T->l);    if(T->r) postOrder(T->r);    printf("%c",T->c); }int main(){    //freopen("input.txt","r",stdin);    while(scanf("%s %s",pre,in)!=EOF){        cur=0,n=strlen(in)-1;        node *T=build(cur,n);        postOrder(T);        cout<<endl;    }    return 0;} /**************************************************************    Problem: 1078    User: cust123    Language: C++    Result: Accepted    Time:0 ms    Memory:1520 kb****************************************************************/

#include <iostream>#include <algorithm>#include <queue>#include <vector>#include <cstring>#include <stack>#include <string>#include <string.h>#include <stdio.h>#include <cmath>#include <map>#include <functional>#include <set>#include <math.h>using namespace std;//1078char pre[27],in[27];int loc,cur;struct node{    char d;    node *l,*r;}Tree[27];int findRoot(char root){    for(int i=0;i<strlen(in);i++)        if(in[i]==root)            return i;}node *creat(){    Tree[loc].l=Tree[loc].r=NULL;    return &Tree[loc++];}node *build(int l,int r){    if(l>r)      return NULL;    node *root=creat();    root->d=pre[cur++];    int idx=findRoot(root->d);    root->l=build(l,idx-1);    root->r=build(idx+1,r);     return root;}void postOrder(node *root){     if(root->l)  postOrder(root->l);    if(root->r)  postOrder(root->r);    printf("%c",root->d);} int main(){    //freopen("input.txt","r",stdin);    while(scanf("%s",pre)!=EOF){        scanf("%s",in);        int l=strlen(in);        loc=0,cur=0;        node *root;        root=build(cur,l-1);        postOrder(root);        cout<<endl;    }    return 0;}/**************************************************************    Problem: 1078    User: cust123    Language: C++    Result: Accepted    Time:10 ms    Memory:1520 kb****************************************************************/


0 0
原创粉丝点击