poj2255 Tree Recovery 二叉樹,這題整我好慘

題目鏈接:http://poj.org/problem?id=2255

題目大意:給你二叉樹的前序遍歷和中序遍歷序列,讓你輸出後序遍歷序列。

思路:使用前序遍歷和中序遍歷序列構造二叉樹,然後用後序遍歷輸出。。。水題。。。

            但是我也不知道爲什麼,也不想去想了,反正少了第46行( if( T->a != 0 ) )會導致輸出多一個NUL。估計是因爲二叉樹中多加入了一個葉子節點。但是爲什麼呢。。。真的不想看了,這道題浪費了我三個小時。。。起初我在fedora上測試樣例數據沒有問題,然後提交後WA。換win7後直接樣例出輸出都不對。最後好不容易發現是上面說的問題。。。心好累   >_<  

///2014.7.16
///poj2255

//Accepted  676K    0MS G++ 1243B   2014-07-17 15:32:51

#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;

char vlr[30],lvr[30];
int length;
struct node{
    char a;
    node * lson, * rson;
    node(){ a=0 ; lson = rson = NULL; }
};
node * T;

void build(int l1,int r1,int l2,int r2,node * & rt){
    rt = new node;
    rt->a = vlr[l1];
    rt->lson = rt->rson = NULL;
    if( l1>=r1 ) return ;
    int loc = l2;
    while( lvr[loc] != vlr[l1] ) loc++;
    if( loc != l2 ){
        int lengthOfLson = loc - l2;
        int x = l1+1;
        int y = l1+lengthOfLson;
        build(x,y,l2,loc-1,rt->lson);
    }
    if( loc != r2 ){
        int lengthOfRson = r2 - loc;
        int x = r1 - lengthOfRson + 1;
        int y = r1;
        build(x,y,loc+1,r2,rt->rson);
    }
    return ;
}

void lrv(node * T){
    if( T==NULL ) return ;
    lrv( T->lson );
    lrv( T->rson );
    if( T->a != 0 )//濾調二叉樹衆多加入的那個神奇的葉子節點
        printf("%c",T->a );
}
int main(){
    // freopen("in","r",stdin);
    // freopen("out","w",stdout);

    while( ~scanf("%s%s",vlr,lvr) ){
        T = NULL;
        length = strlen(vlr);
        build(0,length,0,length,T);
        lrv( T );
        printf("\n");
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章