C语言实现数据结构之 前序遍历、后续遍历、中序遍历

在这里我就不赘述他们的概念了,前辈们写的很详细:
https://blog.csdn.net/qq_34154570/article/details/82700094
https://www.cnblogs.com/lanhaicode/p/10390147.html

我就直接用例题来说明吧

在这里插入图片描述

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <map>
#include <stack>
#include <queue>
#include <vector>
#include <bitset>
#include <set>
#include <utility>
#include <sstream>
#include <iomanip>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
#define inf 0x3f3f3f3f
#define rep(i,l,r) for(int i=l;i<=r;i++)
#define lep(i,l,r) for(int i=l;i>=r;i--)
#define ms(arr) memset(arr,0,sizeof(arr))
//priority_queue<int,vector<int> ,greater<int> >q;
const int N = 1e5 + 10;
const int mod = 1e9+7;
int pos[N],mid[N];
struct node{
    int val;//数值
    node *lson,*rson;//左右孩子
};
node *Solve(int pos_l,int pos_r,int mid_l,int mid_r){//后续和中序的范围
    node *rt;
    int cnt=0;//记录个数
    rt=new node;
    rt->val=pos[pos_r];
    if(pos_l>pos_r || mid_l>mid_r) 
        return nullptr;

    if(pos_l==pos_r){//叶子结点
        rt->lson=rt->rson=nullptr;
        return rt;
    }

    int index;
    for(int i=mid_l;i<=mid_r;i++,cnt++){
        if(mid[i]==rt->val){
            index=i;
            break;
        }
    }

    rt->lson=Solve(pos_l,pos_l+cnt-1,mid_l,index-1);
    rt->rson=Solve(pos_l+cnt,pos_r-1,index+1,mid_r);
}
void Lev(node *rt,int n){//层次遍历,用bfs实现
    queue<node*>q;
    q.push(rt);
    while(!q.empty()){
        node *u=q.front();
        q.pop();
        if(u->lson!=nullptr)
        q.push(u->lson);
        if(u->rson!=nullptr)
        q.push(u->rson);
        if(q.size()==0) printf("%d\n",u->val);
        else printf("%d ",u->val);
    }
}
int main()
{
    #ifndef ONLINE_JUDGE
    freopen("in.txt","r",stdin);
    #endif // ONLINE_JUDGE
    int n;
    scanf("%d",&n);
    for(int i=0;i<n;i++) scanf("%d",&pos[i]);
    for(int i=0;i<n;i++) scanf("%d",&mid[i]);
    node *rt=Solve(0,n-1,0,n-1);
    Lev(rt,n);
    return 0;
}

参考:https://blog.csdn.net/shijie97/article/details/80020494

发布了229 篇原创文章 · 获赞 17 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/c___c18/article/details/104101385
今日推荐