NYOJ-756重建二叉树

点击打开题目链接

1.后序序列的最后一个元素是二叉树的根节点;

2.在中序序列中找到根节点的位置,则中序序列中根节点左边的元素是该根节点的左子树,右边的元素是根节点的右子树;

3.由左子树的节点  在后序序列中找到对应的序列,则所得序列的最后一个元素就是左子树的根节点(右子树构建的方法与此相同)。

所以有递归的方法很方便的就能重建二叉树并得到先序序列。

 
#include <iostream>
#include <cstdio>
#include <cstring>
//#define LOCAL
using namespace std;
typedef char Elemtype;
//----------------------------二叉树结点定义
class BTNode
{
public:
    BTNode(Elemtype _data='#',BTNode *_lchild=NULL,BTNode *_rchild=NULL):data(_data),lchild(_lchild),rchild(_rchild){}

    void Setdata(Elemtype _data) {data=_data;}

    void Setlchild(BTNode *_lchild){lchild=_lchild;}

    void Setrchild(BTNode *_rchild){rchild=_rchild;}

    Elemtype Getdata() {return data;}

    BTNode *Getlchild() {return lchild;}

    BTNode *Getrchild() {return rchild;}

private:
    Elemtype data;
    BTNode *lchild,*rchild;
};

//二叉树功能定义
class BTFun
{
public:
    BTFun(BTNode *_root=NULL):root(_root){}
    ~BTFun() {delete root;}

    void Setroot(BTNode *_root) {root=_root;}
    BTNode *Getroot(){return root;}

    void Preorder(BTNode *t);  //先序遍历

    int Find(char ch,char in[],int in_s,int in_e); //寻找位置
    BTNode *Rebuild(char pre[],char in[],int pre_s,int pre_e,int in_s,int in_e);  //重建二叉树

private:
    BTNode *root;
};

void BTFun::Preorder(BTNode *t)   //得到先序序列并输出
{
    if(t!=NULL)
    {
        cout<<t->Getdata();
        Preorder(t->Getlchild());
        Preorder(t->Getrchild());
    }
}

int BTFun::Find(char ch,char in[],int in_s,int in_e) //返回字符ch在数组in中的位置
{
    int i;
    for(i=in_s;i<=in_e;i++)
        if(in[i] == ch) break;
    return i;
}

BTNode* BTFun::Rebuild(char post[],char in[],int post_s,int post_e,int in_s,int in_e)
{
    if(in_s>in_e) return NULL;
    BTNode *temp=new BTNode(post[post_e]);
    int mid=Find(post[post_e],in,in_s,in_e);
    temp->Setlchild(Rebuild(post,in,post_s,post_s+mid-in_s-1,in_s,mid-1));  //构建左子树
    temp->Setrchild(Rebuild(post,in,post_s+mid-in_s,post_e-1,mid+1,in_e));  //构建右子树
    return temp;   //返回根节点
}

int main()
{
#ifdef LOCAL
    freopen("Input2.txt","r",stdin);
    freopen("Output2.txt","w",stdout);
#endif
    char post[30],in[30];
    while(~scanf("%s%s",post,in))
    {
        BTFun T;
        int len=strlen(post);
        BTNode *t=T.Rebuild(post,in,0,len-1,0,len-1);
        T.Preorder(t);
        cout<<endl;
    }
    return 0;
}
        


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值