AcWing1497. 树的遍历

题目链接:1497. 树的遍历 - AcWing题库

输入:

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

输出:

4 1 6 3 5 7 2

思路:先把树建出来,再进行BFS

代码:

#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N = 35;
int hx[N], zx[N], n;
vector<int> v[N];

void find(int zl, int zr, int hl, int hr, int f){  //建树
    if(zl > zr || hl > hr)  return;    
    v[f].push_back(hx[hr]);    //存入子节点
    int j = 1;
    while(hx[hr] != zx[j]) j++;   //在中序数组中找后序的点
    find(zl, j - 1, hl, hl + j - zl - 1, hx[hr]);  //找左子树
    find(j + 1, zr, hl + j - zl, hr - 1, hx[hr]);  //找右子树
}

void bfs(){   //层序遍历
    queue<int> q;
    q.push(hx[n]);
    while(!q.empty()){
        int p = q.front();  q.pop();
        printf("%lld ", p);
        for(int i = 0; i < v[p].size(); i++){
            q.push(v[p][i]);
        }
    }
}

int32_t main(){
    int tt = 1; 
//    cin >> tt;
    while(tt--){
        cin >> n;
        for(int i = 1; i <= n; i++)  cin >> hx[i];
        for(int i = 1; i <= n; i++)  cin >> zx[i];
        find(1, n, 1, n, 0);
        bfs();
    }
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值