已知中后序遍历-->建立二叉树-->层序输出

二叉树后序:  左  - >  右  - > 根     后序给出的最后一个节点为根节点

二叉树中序:  左  - > 根  - >  右     中序可以在前序的基础上将树的左孩子,右孩子,完全确定。 下面就是一个递归的过程

每次递归过程中 拿当前传入的后序遍历的尾节点 找到中序遍历的该尾节点的位置。并将其划分为左右两个子树。并链接在结构体指针上



#include <iostream>

#include <string.h>
#include <string>
#include <stdlib.h>
#include <stdio.h>
#include <queue>
using namespace std;
typedef struct Treenode * BinTree;
struct Treenode
{
    int Data;
    BinTree Left;
    BinTree Right;
};
BinTree CreatTreeBin(int In[], int Back[],int len)
{
    BinTree T;
    if(len==0)
        return NULL;
    T=(struct Treenode *)malloc(sizeof(struct Treenode));
    T->Data=Back[len-1];
       int i;
    for(i=0;i<len;i++)
    {
        if(In[i]==Back[len-1]) //在中序遍历中,找到后序遍历尾节点位置
        {
            break;
        }
    }
    T->Right=CreatTreeBin(In+i+1,Back+i,len-i-1); //在中序遍历中找到根节点位置后,其右侧即为右子树

    T->Left=CreatTreeBin(In,Back,i); //在中序遍历中找到根节点位置后,其左侧即为左子树

//传参时注意,后序遍历的尾节点已使用,调整传参长度,不使其传入

    return T;
}
int Height(BinTree T) //查询树高
{
    int Theigth,Lheight,Rheight;
    if(!T)
    Theigth =0;
    else
    {
        Lheight=Height(T->Left);
        Rheight=Height(T->Right);
        Theigth=(Lheight>Rheight)?Lheight:Rheight;
        Theigth++;
    }
        return Theigth;
}
void build(BinTree BT) //层序遍历
{
    BinTree T;
    queue <BinTree> q;
    if(!BT)
        return ;
    q.push(BT);
    int flag=0;
    while(q.size())
    {
        T=q.front();
        q.pop();
        if(flag==1)
            printf(" ");
        if(flag==0)
            flag=1;
        printf("%d",T->Data);
        if(T->Left)
        {
            q.push(T->Left);
        }
        if(T->Right)
        {
            q.push(T->Right);
        }
    }
`
}
int main()
{
    int In[100],Back[100];
    int N;
        BinTree T=NULL;
        cin>>N;
    int i;
    for(i=0;i<N;i++)
    {
        cin>>Back[i];
    }
    for(i=0;i<N;i++)
    {
        cin>>In[i];
    }
    T=CreatTreeBin(In,Back,N);
    build(T);
    return 0;
}
/*
9
dbefaghci
defbhgica
*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值