C++根據前序遍歷和後序遍歷建二叉樹

#include<bits/stdc++.h>

using namespace std;

class Node{
    public:
        Node* left;
        Node* right;
        char content;
        Node(){
            left=NULL;
            right=NULL;
        }
};

void postOrder(Node* T){
    if(T!=NULL){
        if(T->left!=NULL) postOrder(T->left);
        if(T->right!=NULL) postOrder(T->right);
        printf("%c",T->content);
    }
}

char pre[30],in[30];

Node* build(int p_start,int p_end,int in_start,int in_end){
    Node* ret=new Node[1];
    ret->content=pre[p_start];
    int rootIdx;
    for(int i=in_start;i<=in_end;i++){
        if(in[i]==pre[p_start]){
            rootIdx=i;
            break;
        }
    } 

    if(rootIdx!=in_start)
        ret->left=build(p_start+1,p_start+(rootIdx-in_start),in_start,rootIdx-1);

    if(rootIdx!=in_end)
        ret->right=build(p_start+1+(rootIdx-in_start),p_end,rootIdx+1,in_end);
    return ret;
}

int main(){
    int num;
    int val,temp1,temp2;
    while(scanf("%s",pre)!=EOF){
        scanf("%s",in);
        int len1=strlen(pre);
        Node* T=build(0,len1-1,0,len1-1);
        postOrder(T);
        printf("\n");
    }
    return 0;
} 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章