您的位置:首页 > 其它

中序和后序确定树结构 树最长路径 叶节点个数

2010-01-17 22:04 585 查看
]#include <iostream>
#include <stack>
#include <string>
#include <list>
using namespace std;

#define MAX_SIZE 30
//树的结构体
struct TreeNode
{
char data;
TreeNode *lChild;
TreeNode *rChild;
public:
TreeNode(char c):data(c),lChild(0),rChild(0){}
};

//辅助
struct Helper{
TreeNode *node;
int index;
public:
Helper(TreeNode *pNode,int idx):node(pNode),index(idx){}
};

int leafCount=0;//叶节点个数
int twoCount=0; //二度节点个数
int record=0; //记录到页节点长度
char Max_Record[MAX_SIZE];
char last_Record[MAX_SIZE];//路径
int maxlength=0;
//还原
void Mid_Post_Restore(string post,string mid,TreeNode *&result);
//前序遍历
void PreorderTraversal(TreeNode *pTree);

int main()
{
string Postorder1;// =  "HIDJKEBMNFOPGCA" ;
string Midorder1;// =  "HDIBJEKAMFNCOGP" ;
cout<<"请输入后序序列!";
cin>>Postorder1;
cout<<"请输入中序序列!";
cin>>Midorder1;

TreeNode *res=0;
Mid_Post_Restore(Postorder1, Midorder1, res);
//前序序列
cout<<"前序序列为:";
PreorderTraversal(res);
cout<<endl<<"叶节点个数:";
cout<<leafCount;
cout<<endl<<"二度节点个数:";
cout<<twoCount;
cout<<endl<<"一条最长路径各结点:";
for(int i=0;i<=maxlength;++i)
cout<<last_Record[i]<<" ";
return 0;
}

//还原
void Mid_Post_Restore(string post,string mid,TreeNode *&result)
{
int pi=post.size()-1; //后序遍历的字符串下标
int mi=0; //中序遍历的下标
char pc;

result = new TreeNode(post[pi]); //后序遍历第一个字符是根
TreeNode *pNode=0;
mi = mid.find(post[pi]); //在中序遍历中查找

list<Helper> helper;
helper.push_back(Helper(0,-1));
helper.push_back(Helper(result,mi));
helper.push_back(Helper(0,mid.size()));
list<Helper>::iterator cur=helper.begin();
cur++;

for(pi=post.size()-2;pi>=0;pi--)
{
pc=post[pi];
mi=mid.find(pc);

while(true)
{
if(mi>(*cur).index)
{
pNode =new TreeNode(pc);
(*cur).node->rChild=pNode;
cur++;
cur=helper.insert(cur,Helper(pNode,mi));
break;
}else
{
list<Helper>::iterator nxt=cur;
cur--;
if((*cur).index<mi && mi<(*nxt).index)
{
pNode=new TreeNode(pc);
(*nxt).node->lChild=pNode;
helper.erase(nxt);
cur++;
cur=helper.insert(cur,Helper(pNode,mi));
break;
}else
{
helper.erase(nxt);
continue;
}
}
}
}
}

//前序遍历
void PreorderTraversal(TreeNode *pTree)
{
if(pTree!=NULL)
{
Max_Record[record]=pTree->data;
if(pTree->lChild==NULL && pTree->rChild==NULL)
{
if(record>maxlength)
{
for(int i=0;i<=record;++i)
last_Record[i]=Max_Record[i];
maxlength=record;
}
leafCount++;
}
if(pTree->lChild!=NULL && pTree->rChild!=NULL)
twoCount++;
cout<<pTree->data;
record++;
PreorderTraversal(pTree->lChild);
PreorderTraversal(pTree->rChild);
record--;
}
}


以上是具体代码,希望对某些计算机学习者有帮助。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐