(13)数据结构-先序中序还原二叉树

1、问题描述
给定节点个数,及未知二叉树的先序遍历和中序遍历,求该二叉树的层序遍历。

2、问题思路
给定二叉树的中序遍历 与先序,后序,层序任一组合可得到唯一一个二叉树,本文以先序遍历为例。
先序遍历提供根节点,得到根节点以后,在中序遍历结果中可区分出来左子树与右子树以及根节点的位置k。有了k以后,问题就变成还原k的左右两侧二叉树,问题规模进一步缩小,也就形成了递归(递归式)。在递归过程中,子树的遍历结果在递归过程中长度不断减小,当长度为0的时候,递归就终止了(递归出口)。

3、输入样例
在这里插入图片描述

输入:
8
8 7 5 1 4 6 3 2
1 5 7 4 8 3 6 2

输出:
8 7 6 5 4 3 2 1

4、代码实现


#include <iostream>
#include <queue>
using namespace std;
#define MaxSize 50

typedef int ElemType;
typedef struct node{
    
    
    ElemType data;
    struct node*lchild;
    struct node*rchild;
}BiNode,*BiTree;

BiTree CreateBiTree(int n, ElemType Pre[], ElemType In[]);
void Level(BiTree T);
int main(){
    
    
    ElemType Pre[MaxSize];
    ElemType In[MaxSize];
    int n;
    cin >> n;

    for (int i = 0; i < n; i++){
    
    
        cin >> Pre[i];
    }

    for (int i = 0; i < n; i++){
    
    
        cin >> In[i];
    }

    BiTree T = CreateBiTree(n,Pre,In);
    Level(T);
	
    return 0;
}

BiTree CreateBiTree(int n, ElemType Pre[], ElemType In[]){
    
    
    if (n == 0){
    
    
        return NULL;
    }
    int k = 0;
    for(;Pre[0]!=In[k]; k++);

    ElemType LPre[MaxSize];
    ElemType LIn[MaxSize];
    for(int i = 0; i < k; i++){
    
    
        LPre[i] = Pre[i+1];
        LIn[i] = In[i];
    }

    ElemType RPre[MaxSize];
    ElemType RIn[MaxSize];
    for(int i = 0; i < n-k-1; i++){
    
    
        RPre[i] = Pre[k+1+i];
        RIn[i] = In[k+1+i];
    }

    BiTree T = new BiNode;
    T->data = Pre[0];
    //在纸上画画这里的长度为什么是k和n-k-1。
    T->lchild = CreateBiTree(k,LPre,LIn);
    T->rchild = CreateBiTree(n-k-1,RPre,RIn);

    return T;
}

//如果层序遍历不会,在我的另一篇文章有讲到
void Level(BiTree T){
    
    
    queue<BiTree> q;
    q.push(T);
    while(!q.empty()){
    
    
        BiTree temp = q.front();
        q.pop();
        cout << temp->data << " ";

        if(temp->lchild){
    
    
            q.push(temp->lchild);
        }
        if(temp->rchild){
    
    
            q.push(temp->rchild);
        }
    }
}

おすすめ

転載: blog.csdn.net/xdg15294969271/article/details/120486280