【算法練習】數據結構二叉樹 百練poj2255:重建二叉樹

http://bailian.openjudge.cn/practice/2255

2255:重建二叉樹

總時間限制: 

1000ms

 

內存限制: 

65536kB

描述

給定一棵二叉樹的前序遍歷和中序遍歷的結果,求其後序遍歷。

輸入

輸入可能有多組,以EOF結束。
每組輸入包含兩個字符串,分別爲樹的前序遍歷和中序遍歷。每個字符串中只包含大寫字母且互不重複。

輸出

對於每組輸入,用一行來輸出它後序遍歷結果。

樣例輸入

DBACEGF ABCDEFG
BCAD CBAD

樣例輸出

ACBFGED
CDAB

題目就是重建二叉樹,就是利用前序、中序可以唯一地確定一棵二叉樹來進行遞歸地實現

 

在實現的過程中設置前序/中序遍歷的閉區間,不斷地修改該閉區間的值進行改變,

注意實現的過程中自己的問題:

1、重建二叉樹的時候要記得判斷左子樹和右子樹是否爲空再進行遞歸重建

2、後序遍歷的時候也要記得判斷左子樹和右子樹是否爲空

 

AC代碼:

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

struct Node{
    char c;
    Node *lchild;
    Node *rchild;
}tree[200];
int loc;
char str1[100],str2[100];

//建立新的結點
Node *create(){
    tree[loc].lchild=tree[loc].rchild=NULL;
    return &tree[loc++];
}

Node *build(Node *root,int q1,int q2,int z1,int z2){
    root=create();
    char cr=str1[q1];  //根節點
    root->c=cr;

    int idx=z1;
    for(;idx<=z2;idx++){
        if(str2[idx]==cr)
            break;
    }

    //考慮子樹不爲空啊
    //如果左子樹不爲空
    if(idx!=z1){
        root->lchild=build(root->lchild,q1+1,q1+(idx-z1),z1,idx-1);
    }
    if(idx!=z2){
        root->rchild=build(root->rchild,q1+(idx-z1)+1,q2,idx+1,z2);
    }

    return root;

}

void  PostOrder(Node *root){
    //一定要注意是不爲空的時候才能進去遍歷子樹
    if(root->lchild!=NULL){
        PostOrder(root->lchild);
    }
    if(root->rchild!=NULL){
        PostOrder(root->rchild);
    }

    cout<<root->c;
}
int main(){

    while(cin>>str1){
        cin>>str2;
        loc=0;
        //根據前序遍歷和中序遍歷建立二叉樹
        Node *root=NULL;
        int len1=strlen(str1);
        int len2=strlen(str2);
        root=build(root,0,len1-1,0,len2-1);  //前序遍歷左邊界 有邊界
        PostOrder(root);
        cout<<endl;

    }
    return 0;
}

 

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