从先序中序重建二叉树输出层序后序

#include <iostream>
#include <vector>
#include <string>
#include <queue>
#include <cstring>
#define MAX 10000
using namespace std;

struct tree
{
    int data;
    tree* left;
    tree* right;
    tree()
    {
        data = 0;
        left = NULL;
        right = NULL;
    }
};
tree* root;
int front[100000];
int mid[100000];
int n;
tree* build(int *front,int *mid,int n)
{
    if(n == 0)
        return NULL;
    int x = 0;
    while(front[0]!=mid[x])
        x++;
    tree *t = new tree();
    t->data = mid[x];
    t->left = build(front+1,mid,x);
    t->right = build(front+1+x,mid+1+x,n-x-1);
    return t;
}

void order(tree* t)
{
    queue<tree *> tmp;
    tmp.push(t);
    while(!tmp.empty())
    {
        tree * tt;
        tt = tmp.front();
        tmp.pop();
        cout<<tt->data<<" ";
        if(tt->left != NULL)
            tmp.push(tt->left);
        if(tt->right != NULL)
            tmp.push(tt->right);
    }
}
void PostOrder(tree* t)
{
    if(t)
    {
        PostOrder(t->left);
        PostOrder(t->right);
        cout<<t->data<<" ";
    }
}
int main()
{
    cin>>n;
    for (int i = 0; i < n; ++i)
        cin>>front[i];
    for (int i = 0; i < n; ++i)
        cin>>mid[i];
    root = build(front,mid,n);
    order(root);
    cout<<endl;
    PostOrder(root);
    return 0;
}

 

posted @ 2020-12-14 19:37  ananasaa  阅读(157)  评论(0编辑  收藏  举报