由中序序列和后序序列确定一棵二叉树

 

 

代码:

#include<iostream>
#include<algorithm>
#include<vector>
#include<math.h>
#include<stdio.h>
#include<string.h>
#include<map>
#include<queue>
#include<utility>
#define ll long long
#define maxn 1005
using namespace std;

int in[maxn];//中序序列
int hou[maxn];//后序序列

struct node
{
    int data;
    node* lchild;
    node* rchild; 
};

int N,M;

node* create(int houL,int houR,int inL,int inR)
{
    if(houL > houR)//当二叉树没有左右节点的时候,说明是叶子节点,即空子树时递归结束
        return NULL;
    
    node* root = new node;
    root->data = hou[houR];//将hou的houL值放入到结构体中,这里是确定二叉树的根,即后序遍历的最后一个节点
    int i ;
    for(i = inL; i <= inR;i++)//在中序序列中区分左子树和右子树 
    {
        if(in[i] == hou[houR]) 
            break;
    }
    int numLeft = i - inL;//看左边是否还有节点 
    //注意这里没有对numLeft的数目进行判断!! 
 
    root->lchild = create(houL,houL+numLeft-1,inL,i-1);
    root->rchild = create(houL+numLeft,houR-1,i+1,inR); 
    return root;
}

//inOrder
void inOrder(node* root)//以中序序列输出
{
    if(root->lchild != NULL ) //输出左节点
        inOrder(root->lchild);
    cout << root->data << " ";//输出根节点
    if(root->rchild != NULL ) 
        inOrder(root->rchild);//输出右节点
}
void preOrder(node* root)//以先序序列输出
{
    cout << root->data << " ";//
    if(root->lchild!=NULL)
        preOrder(root->lchild);//
    if(root->rchild!=NULL)
        preOrder(root->rchild);//
}
void houOrder(node* root)//后序序列输出
{
    if(root->lchild!=NULL)//
        houOrder(root->lchild);
    if(root->rchild!=NULL)//
        houOrder(root->rchild);
    cout << root->data << " ";//
}

int main()
{
    cin >>  N;
    int i;
    for(i = 0;i< N;i++) 
        cin >> in[i];
    for(i = 0;i< N;i++) 
        cin >> hou[i];
    node* root;
    root = create(0,N-1,0,N-1);
    preOrder(root);//输出先序序列
    cout<<endl;
}
// 8
// 7 2 3 4 6 5 1 8  中序
// 2 7 4 6 3 1 8 5  后序

//5 3 7 2 6 4 8 1   先序

 

 

posted @ 2019-11-28 16:32  知道了呀~  阅读(4458)  评论(0编辑  收藏  举报