1020. Tree Traversals (25)

題目鏈接:https://www.patest.cn/contests/pat-a-practise/1020


題目大意:已知樹的後序遍歷和中序遍歷,求該樹的層次遍歷


解題思路:

  • 先根據後序和中序確定樹的結構
  • 再進行層次遍歷即可

代碼如下:

#include<iostream>
#include<vector>
#include<queue>
using namespace std;
struct Node{
    int data;
    Node* lchild;
    Node* rchild;
};
int post[32];//後序遍歷序列
int in[32];//中序遍歷序列
Node* create(int pL,int pR,int iL,int iR){//pL,pR爲後序序列左右端點;iL,iR爲中序序列左右端點
    if(pL>pR)return NULL;
    Node* root=new Node;//建立根節點
    root->data=post[pR];
    int index;
    for(index=iL;index<=iR;index++){//在中序序列中找到根節點
        if(in[index]==post[pR])
            break;
    }
    int numleft=index-iL;
    root->lchild=create(pL,pL+numleft-1,iL,index-1);//遞歸地建立左子樹
    root->rchild=create(pL+numleft,pR-1,index+1,iR);//遞歸地建立右子樹
    return root;
}
int firstflag=0;//標記是否輸出的爲第一個節點
void levelOrder(Node *p){
    queue<Node*> que;
    que.push(p);
    while(!que.empty()){
        Node* tmp=que.front();
        que.pop();
        if(firstflag!=0)//若不是第一個節點,先輸出空格
            cout<<" ";
        cout<<tmp->data;//再輸出值
        firstflag=1;
        if(tmp->lchild!=NULL)
            que.push(tmp->lchild);
        if(tmp->rchild!=NULL)
            que.push(tmp->rchild);
    }
}
int main(){
    int n;
    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);
    levelOrder(root);
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章