输入前序和中序序列,建树,输出其前中后序以及层序遍历序列

例如输入7
4 1 3 2 6 5 7
1 2 3 4 5 6 7
输出
4132657
1234567
2315764
4163572

#include<cstdio>
#define maxn 16
#include<algorithm>
#include<vector>
#include<cmath>
#include<iostream>
#include<queue>
using namespace std;
vector<int>preorder;
vector<int>inorder;
//利用前序序列和中序序列递归建树,递归边界是序列长度小于等于0,
//在递归程序中,输入序列左右两端点下标,先处理先序序列,得到序列对应树的根,然后处理中序序列,得到
//对应树的左子树右子树序列的左右端点下标,递归进行此过程,直到递归边界
struct node
{
    int data;
    node* lchild;
    node* rchild;
};
node* build(int preL,int preR,int inL,int inR )
{
    if(preL>preR){
        return NULL;
    }
    node *root=new node;
    root->data=preorder[preL];
    root->lchild=NULL;
    root->rchild=NULL;
    int index;
    for(index=inL;index<=inR;index++){
        if(inorder[index]==preorder[preL]){
            break;
        }
    }
    root->lchild=build(preL+1,preL+index-inL,inL,index-1);//index-inL是前序序列左子树的长度
    root->rchild=build(preL+index-inL+1,preR,index+1,inR);
    return root;
}
node* create(int x)
{
    node* Node=new node;
    Node->data=x;
    Node->lchild=NULL;
    Node->rchild=NULL;
    return Node;
}
void Find(node *root,int x,int newdata)
{
    if(root==NULL)return ;
    if(root->data==x){
        root->data=newdata;
    }
    Find(root->lchild,x,newdata);
    Find(root->rchild,x,newdata);

}
void Preorder(node * root)
{
    if(root==NULL){
        return;
    }
    printf("%d",root->data);
    Preorder(root->lchild);
    Preorder(root->rchild);
}
void Inorder(node *root)
{
    if(root==NULL){
        return ;
    }
    Inorder(root->lchild);
    printf("%d",root->data);
    Inorder(root->rchild);
}
void postorder(node *root)
{
    if(root==NULL){
        return ;
    }
    postorder(root->lchild);
    postorder(root->rchild);
    printf("%d",root->data);
}
void Layerorder(node *root)
{
    if(root==NULL){
        return ;
    }
    queue<node*>q1;
    q1.push(root);
    node *temp;
    while(!q1.empty()){
        temp=q1.front();
        printf("%d",temp->data);
        q1.pop();
        if(temp->lchild!=NULL){
            q1.push(temp->lchild);
        }
        if(temp->rchild!=NULL){
            q1.push(temp->rchild);
        }
    }

}
int main()
{
    int length;
    scanf("%d",&length);
    int temp;
    for(int i=0;i<length;i++){
        scanf("%d",&temp);
        preorder.push_back(temp);
    }
    for(int i=0;i<length;i++){
        scanf("%d",&temp);
        inorder.push_back(temp);
    }
    node* root;
    root=build(0,preorder.size()-1,0,inorder.size()-1);
    Preorder(root);
    printf("\n");
    Inorder(root);
    printf("\n");
    postorder(root);
    printf("\n");
    Layerorder(root);
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值