根據後序與中序遍歷建樹層序遍歷輸出

在我心裏只要是二叉樹就一定與遞歸有千絲萬縷的關係,因此先遞歸建立左子樹,再遞歸右子樹,

像遞歸這種東西,一定要站在一個高度去看他,如果想的太複雜了會越陷越深,所以寫代碼是隻要

給他一個宏觀上的指令,就可以了。層序遍歷吧,代碼很簡單,看一遍應該就理解了。

#include <cstdio>
#include <cstring>
#include <iostream>
#include <queue>
#include <cstdlib>

using namespace std;

int mid[100],post[100],pre[100];
int n;
struct node
{
    int c;
    node *lchild,*rchild;
};

//根據後序遍歷與中序遍歷遞歸建樹
node *postMidCreatTree(int len, int *mid, int *post)
{
    int i;
    if(len<=0)
        return NULL;
    node *p = (node *)malloc(sizeof(node));
    p->lchild = p-> rchild = NULL;
    p->c = post[len-1];
    for(i=0; i<n; ++i)
        if(mid[i] == post[len-1])
            break;
    int l=i;
    p->lchild = postMidCreatTree(l,mid,post);
    p->rchild = postMidCreatTree(len-l-1,mid+l+1,post+l);
    return p;
}

//層序遍歷
int levelTraverseTree(node *head)
{
    queue<node *>q;
    q.push(head);
    int i=0;

    while(!q.empty())
    {
        node *t;
        t = q.front();
        q.pop();
        pre[i++] = t->c;
        if(t->lchild)
        q.push(t->lchild);
        if(t->rchild)
        q.push(t->rchild);
    }

    return i;
}

int main()
{
    cin >> n;

    for(int i=0; i<n; ++i)
        cin >> post[i];
    for(int i=0; i<n; ++i)
        cin >> mid[i];

    node *head = (node *)malloc(sizeof(node));
    head->lchild = head->rchild = NULL;
    head = postMidCreatTree(n,mid,post);

    int len = levelTraverseTree(head);

    for(int i=0; i<len-1; ++i)
        cout << pre[i] << " ";
    cout << pre[len-1] << endl;
    return 0;
}


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