L2-006 树的遍历 (25 分)

给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。

输入格式:

输入第一行给出一个正整数N(≤30),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。

输出格式:

在一行中输出该树的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。

输入样例:

7
2 3 1 5 7 6 4
1 2 3 4 5 6 7

输出样例:

4 1 6 3 5 7 2

题解:以前做的全是字符的树,这回来个数字的,不能简简单单用指针来实现了~。用左边和右边来控制就好了~~

#include<bits/stdc++.h>
using namespace std;
struct node
{
    node *l,*r;
    int data;
};
int middle[50],finall[50];
int n;
node *creat(int l1,int r1,int l2,int r2)//中序的区间,后序的区间
{
    if(l2>r2||l1>r1)
        return NULL;
    node *root=new node;
    root->data=finall[r2];//树根等于后序遍历的最后一个
    root->l=NULL,root->r=NULL;
    int i;
    for(i=l1;i<=r1;i++)
    {
        if(middle[i]==finall[r2])//找到根在中序的位置
            break;
    }
    int num=i-l1;
    root->l=creat(l1,i-1,l2,l2+num-1);//画个图模拟一下,就好了
    root->r=creat(i+1,r1,l2+num,r2-1);
    return root;
}
void layershow(node *root)
{
    queue<node*>que;
    if(root)
    {
        que.push(root);
        cout<<que.front()->data;
    }
    while(!que.empty())
    {
        node *root=que.front();
        que.pop();
        if(root->l)
        {
            cout<<" "<<root->l->data;
            que.push(root->l);
        }
        if(root->r)
        {
            cout<<" "<<root->r->data;
            que.push(root->r);
        }
    }
}
int main()
{
    cin>>n;
    for(int i=0;i<n;i++)
        cin>>finall[i];
    for(int i=0;i<n;i++)
        cin>>middle[i];
    node *root=NULL;
    root=creat(0,n-1,0,n-1);
    layershow(root);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43824158/article/details/88604985