1020 Tree Traversals (25 分)建树+层次遍历bfs模板

一、qisiwole!!!找了两小时的错,输出只有4 1,还以为是create的原因,调试的时候显示left无法读取内存,那是因为没有孩子啦,返回的是null,不指向任何空间,是因为把if(now->right!=NULL) 写成了等于。
二、不明白为什么在vs调试的时候queue<node*> q;写在bfs中会报错,得放在外边,不过结果正常。

#include<iostream>
#include<queue>
using namespace std;
const int maxn=50;
int n;
int post[maxn],in[maxn];
struct node{
    
    
    int data;
    node *left,*right;
};
node* create(int postL,int postR,int inL,int inR)
{
    
    
    int i;
    if(postL>postR)
        return NULL;
    node *root=new node;
    root->data=post[postR];
    for(i=inL;i<=inR;i++)
    {
    
    
        if(in[i]==post[postR])
            break;
    }
    int numleft=i-inL;
    root->left=create(postL,postL+numleft-1,inL,i-1);
    root->right=create(postL+numleft,postR-1,i+1,inR);
    return root;
}
int num=0;
void bfs(node* root){
    
    
    queue<node*> q;
    q.push(root);
    while(!q.empty()){
    
    
        node* now=q.front();
        q.pop();
        printf("%d",now->data);
        num++;
        if(num<n) printf(" ");
        if(now->left!=NULL) q.push(now->left);
        if(now->right!=NULL) q.push(now->right);
    }
}
int main()
{
    
    
    cin>>n;
    for(int i=0;i<n;i++)
        cin>>post[i];
    for(int i=0;i<n;i++)
        cin>>in[i];
    node* root=create(0,n-1,0,n-1);
    bfs(root);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42835526/article/details/113660140