GPLT L2-011. 玩转二叉树【递归建树+bfs】

题目:玩转二叉树

思路:递归建树,输出时先右后左入队即可

代码:

#include 
#include 
#include 
#include 
using namespace std;
const int maxn = 35;
int before[maxn],maid[maxn],lch[maxn],rch[maxn],n;
int build(int l1,int r1,int l2,int r2){
    if(l1 > r1) return 0;
    int root = before[l1];
    int p = 0;
    for(int i=l2;i<=r2;i++){ if(root != maid[i])p++;else break; }
    lch[root] = build(l1+1,l1+p,l2,l2+p-1);
    rch[root] = build(l1+p+1,r1,l2+p+1,r2);
    return root;
}
void bfs(int start){
    queueQ;
    Q.push(start);
    while(!Q.empty()){
        int pre = Q.front();Q.pop();
        printf("%d",pre);
        if(rch[pre]) Q.push(rch[pre]);
        if(lch[pre]) Q.push(lch[pre]);
        if(!Q.empty()) printf(" ");
    }
}
int main()
{
    while(cin >> n){
        for(int i=0;i


你可能感兴趣的:(---数据结构---,GPLT,天梯赛)