您的位置:首页 > 其它

NYOJ-756重建二叉树

2013-09-07 08:51 357 查看
点击打开题目链接

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: