pat A 1086

下面是错误的。不能通过。原因在于if语句后面多了个分号。害的我找了一上午。

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <stdio.h>
#include <math.h>
#include <queue>
#include <stack>
#include <cstring>
using namespace std;
stack<int> st;
int pre[50];
int in[50];
int num;
struct node{
    int data;
    node* l;
    node* r;
};
node* create(int pre1,int pre2,int in1,int in2){

    if(pre1>pre2){
            return NULL;

    }
    node* root=new node;
    root->data=pre[pre1];
    int k;
    for(k=in2;k>=in1;k--){
        if(in[k]==pre[pre1]);
        break;//经常在这里犯错。以为k指向根数值的前一个。导致后续出错!!!
    }
    root->l=create(pre1+1,pre1+k-in1,in1,k-1);

    root->r=create(pre1+k-in1+1,pre2,k+1,in2);
    return root;
}
int n=0;
void postorder(node* root){
    if(root==NULL)
        return;
    postorder(root->l);
    postorder(root->r);

    printf("%d",root->data);
    n++;
    if(n<num) printf(" ");
}

int main(){

    scanf("%d",&num);
    char str[5];
    int x,index1=0,index2=0;
    for(int i=0;i<num*2;i++){
        scanf("%s",str);
        if(strcmp(str,"Push")==0){
            scanf("%d",&x);
            pre[index1++]=x;
            st.push(x);
        }else{
            in[index2++]=st.top();
            st.pop();
        }
    }
     node* root=create(0,num-1,0,num-1);
     postorder(root);
     return 0;
}

改正之后如下

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <stdio.h>
#include <math.h>
#include <queue>
#include <stack>
#include <cstring>
using namespace std;
stack<int> st;
int pre[50];
int in[50];
int num;
struct node{
    int data;
    node* l;
    node* r;
};
node* create(int pre1,int pre2,int in1,int in2){

    if(pre1>pre2){
            return NULL;

    }
    node* root=new node;
    root->data=pre[pre1];
    int k;
    for(k=in2;k>=in1;k--){
        if(in[k]==pre[pre1])
        break;//经常在这里犯错。以为k指向根数值的前一个。导致后续出错!!!
    }
    root->l=create(pre1+1,pre1+k-in1,in1,k-1);

    root->r=create(pre1+k-in1+1,pre2,k+1,in2);
    return root;
}
int n=0;
void postorder(node* root){
    if(root==NULL)
        return;
    postorder(root->l);
    postorder(root->r);

    printf("%d",root->data);
    n++;
    if(n<num) printf(" ");
}

int main(){

    scanf("%d",&num);
    char str[5];
    int x,index1=0,index2=0;
    for(int i=0;i<num*2;i++){
        scanf("%s",str);
        if(strcmp(str,"Push")==0){
            scanf("%d",&x);
            pre[index1++]=x;
            st.push(x);
        }else{
            in[index2++]=st.top();
            st.pop();
        }
    }
     node* root=create(0,num-1,0,num-1);
     postorder(root);
     return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值