题目1078:二叉树遍历

#include "iostream"
#include "stdio.h"
#include <vector>
#include <cstring>
#include <algorithm>
#include <string>
#include <string.h>
#include <stack>
using namespace std;
//1078
char 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;
//1078
char 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
****************************************************************/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值