数据结构实习 - problem K 用前序中序建立二叉树并以层序遍历和后序遍历输出

用前序中序建立二叉树并以层序遍历和后序遍历输出

writer:pprp

实现过程主要是通过递归,进行分解得到结果
代码如下:
#include <iostream>
#include <queue>
#include <cstdio>
#include <cstring>
using namespace std;
const int N = 1000;
struct tree
{
    tree* l;
    tree* r;
    int data;
    tree()
    {
        l = NULL;
        r = NULL;
        data = 0;
    }
};
void LevelOrder(tree * root)
{
    queue<tree*> q;
    tree * p = root;
    q.push(p);
    while(!q.empty())
    {
        p = q.front();
        q.pop();
        cout << p->data << " ";
        if(p->l != NULL)
            q.push(p->l);
        if(p->r != NULL)
            q.push(p->r);
    }
}

void PostOrder(tree * root)
{
    if(root != NULL)
    {
        PostOrder(root->l);
        PostOrder(root->r);
        cout << root->data << " ";
    }
}

tree * CreateTree(int* pre, int* in, int n)
{
    tree * node = NULL;
    int lpre[N], rpre[N];
    int lin[N],rin[N];
    memset(lin,0,sizeof(lin)),memset(rin,0,sizeof(rin)),
           memset(lpre,0,sizeof(lpre)),memset(rpre,0,sizeof(rpre));
    if(n == 0)
        return NULL;
    node = new tree;
    node->data = pre[1];
    int lincnt = 1, rincnt = 1;
    int lprecnt = 1, rprecnt = 1;
// deal with in order
    for(int i = 1; i <= n ; i++)
    {
        if(in[i]!=pre[1])
        {
            if(i <= lincnt)
                lin[lincnt++] = in[i];
            else
                rin[rincnt++] = in[i];
        }
    }
    lincnt--,rincnt--;
// deal with pre order
    for(int i = 2; i <= n ; i++)
    {
        if(i < (lincnt+2))
            lpre[lprecnt++] = pre[i];
        else
            rpre[rprecnt++] = pre[i];
    }
    lprecnt--,rprecnt--;
    node->l = CreateTree(lpre,lin,lincnt);
    node->r = CreateTree(rpre,rin,rincnt);
    return node;
}
int main()
{
    int n;
    cin >> n;
    int *pre, *in;
    pre = new int[n+1];
    in = new int[n+1];
    for(int i = 1; i <= n ; i++)
        cin >> pre[i];
    for(int i = 1; i <= n ; i++)
        cin >> in[i];
    tree * root = CreateTree(pre,in,n);
    LevelOrder(root);
    cout << endl;
    PostOrder(root);
    return 0;
}

posted @ 2017-10-24 20:10  pprp  阅读(275)  评论(0编辑  收藏  举报