zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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

序列二叉树 确定 中序 前序
2023-09-14 08:56:53 时间

 

1、先序序列确定根节点

2、后序序列区分左右子树

#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 pre[maxn];//先序序列

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

int N,M;

node* create(int preL,int preR,int inL,int inR)
{
    if(preL > preR)//当二叉树没有左右节点的时候,说明是叶子节点,即空子树时递归结束
        return NULL;
    
    node* root = new node;
    root->data = pre[preL];//将pre的preL值放入到结构体中,这里是确定二叉树的根,即先序遍历的第一个节点
    int i ;
    for(i = inL; i <= inR;i++)//在中序序列中区分左子树和右子树 
    {
        if(in[i] == pre[preL]) 
            break;
    }
    int numLeft = i - inL;//看左边是否还有节点 
    //注意这里没有对numLeft的数目进行判断!! 
    root->lchild = create(preL+1,preL+numLeft,inL,i-1);
    root->rchild = create(preL+numLeft+1,preR,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 >> pre[i];
    node* root;
    root = create(0,N-1,0,N-1);
    houOrder(root);  
}
// 8
// 7 2 3 4 6 5 1 8  中序
// 5 3 7 2 6 4 8 1  先序

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