二叉樹建樹(層序+中序)


題目描述

給一棵二叉樹的層序遍歷序列和中序遍歷序列,求這棵二叉樹的先序遍歷序列和后序遍歷序列。

 

輸入

每個輸入文件中一組數據。

第一行一個正整數N(1<=N<=30),代表二叉樹的結點個數(結點編號為1~N)。接下來兩行,每行N個正整數,分別代表二叉樹的層序遍歷序列和中序遍歷序列。數據保證序列中1~N的每個數出現且只出現一次。

 

輸出

輸出一行,包含N個正整數,代表二叉樹的先序遍歷序列。每行末尾不輸出額外的空格。

 

樣例輸入

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

樣例輸出

3 5 2 4 6 7 1
 
 
 
思路:層序的第一個節點是根節點,那么接下來就是找其左子樹和右子樹了,然后遞歸建樹就行了。
 

 


思路和中序+其他建樹一樣,遞歸建立即可,同樣首先要找到每次遞歸需要的參數,左子樹、右子樹的層序遍歷和中序遍歷的左右端點。

 

1、層序第一個節點為根節點,按值找到中序中的根結點記錄位置為pos。
 
2、從層序的第二個結點開始遍歷序列,每次去中序中找該結點的值,如果找到位置小於pos,則說明在左子樹,插入左子樹的層序序列;如果找到位置大於pos,則說明在右子樹,插入右子樹的層序序列。比如層序第二個是5,在中序中找5,其位置在pos左邊,說明在左子樹中,插入左子樹,接着找4, 4在右邊插入右子樹,依次插入即可。
 
(因為拆分成左右子樹的時候,左子樹和右子樹的層序遍歷和整棵樹的層序遍歷保持一致。直到遍歷完成,此時LayerLeft和LayerRight也建立好了,遞歸即可。)
 
 
/**
* Copyright(c)
* All rights reserved.
* Author : Mered1th
* Date : 2019-02-21-19.51.25
* Description : build
*/
#include<cstdio>
#include<cstring>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<string>
#include<unordered_set>
#include<map>
#include<vector>
#include<set>
using namespace std;
const int maxn=10000;
struct Node{
    int data;
    Node* lchild;
    Node* rchild;
    Node(int _data){
        data=_data;
        lchild=NULL;
        rchild=NULL;
    }
};
vector<int> layer,in;
int n;

Node* buildBiTree(vector<int> layer,vector<int> in,int inL,int inR)
{
    if(layer.size()==0 || inL>inR) return nullptr;
    int rootVal=layer[0];
    Node* root=new Node(rootVal);
    int pos=inL;
    while(in[pos]!=rootVal) pos++;

    vector<int> layerLeft,layerRight;//存放左、右子樹的層序序列
    for(int i=1;i<layer.size();i++){
        int j;
        for(j=inL;j<pos;j++){
            if(layer[i]==in[j]){
                layerLeft.push_back(layer[i]);  //如果在pos前找到,插入左子樹
                break;
            }
        }
        if(j==pos) layerRight.push_back(layer[i]);  //超過pos,插入右子樹(層序遍歷保持左右子樹層序遍歷順序的一致性)
    }
    root->lchild=buildBiTree(layerLeft,in,inL,pos-1);
    root->rchild=buildBiTree(layerRight,in,pos+1,inR);

    return root;
}
vector<int> ans;
void pre(Node * root)
{
    if(root!=NULL)
    {
        ans.push_back(root->data);
        pre(root->lchild);
        pre(root->rchild);
    }
}

int main(){
#ifdef ONLINE_JUDGE
#else
    freopen("1.txt", "r", stdin);
#endif
    int temp;
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>temp;
        layer.push_back(temp);
    }
    for(int i=0;i<n;i++) {
        cin>>temp;
        in.push_back(temp);
    }
    Node* root=NULL;
    root=buildBiTree(layer,in,0,n-1);
    pre(root);
    int len=ans.size();
    for(int i=0;i<len;i++){
        printf("%d",ans[i]);
        if(i!=len-1) printf(" ");   //控制格式輸出
    }
    return 0;
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM