5-5 Tree Traversals Again

点击打开链接

push顺序给出先序遍历,pop顺序给出中序遍历,根据先序中序直接求出后序,并不需要构建图

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<queue>
#include<algorithm>
#include<map>
#include<vector>
#include<cstring>
#include<math.h>
#include<stack>
using namespace std;


int N;
int pre[100],in[100],post[100];
void solve(int prel,int inl,int postl,int n)//PreL代表从PreOrder当前第一个节点的位置,InL,PostL同理。n代表传入的规模
{
    if(n==0) return;
    if(n==1) { post[postl] = pre[prel]; return; }
    int root = pre[prel]; //找出当前的根节点
    post[postl+n-1] = root;//把根节点插入到后序遍历的数组中
    int i;
    for( i=0;i<n;i++)  //找到在中序遍历数组中此时root位置
        if(in[inl+i] == root) break;
    int L=i;  //L表示此时root左边节点个数
    int R=n-L-1; //R表示此时root右边节点个数
    solve(prel+1, inl,postl,L); //分而治之,对左子树递归
    solve(prel+L+1,inl+L+1,postl+L,R); //对右子树递归
}




int main()
{
    cin>>N;
    int x,npre=0,nin=0;
    string ss;
    stack<int >st;
    while(1)
    {
        cin>>ss;
        if(ss[1]=='u')
        {
            cin>>x;
            st.push(x);
            pre[npre++]=x;
            getchar();
        }
        else if(ss[1]=='o')
        {
            x=st.top();
            st.pop();
            in[nin++]=x;
            getchar();
        }
        if(npre==N&&nin==N)
            break;
    }
    solve(0,0,0,N);
    for(int i=0;i<N;i++)
    {
        if(i>0)
            cout<<" ";
        cout<<post[i];
    }






}














评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值