链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=221
由于二叉树本身是递归的结构,前序遍历的第一个节点一定是根节点,而通过对后序的结果进行查找,后续第一个节点的距离与前序第一个相同的结点的距离即为左子树的节点的个数,同理右子树同理、
#include<iostream>
#include<stdio.h>
#include<cstring>
#define Max 27
using namespace std;
char pstr[Max],instr[Max];
struct Node
{
char n;
Node *leftchild,*rightchild;
Node(char s):n(s),leftchild(NULL),rightchild(NULL) {}
};
void postorder(Node *roo);
Node* Rebulid(char pstr[],char instr[],int len);
int main()
{
while(scanf("%s%s",&pstr,&instr)!=EOF)
{
Node *root=Rebulid(pstr,instr,int(strlen(pstr)));
postorder(root);
cout<<endl;
}
system("pause");
return 0;
}
Node* Rebulid(char pstr[],char instr[],int len)
{
if(len<=0) return NULL;
Node *newNode=new Node(pstr[0]);
int k,temp;
for(k=0;k<len;++k)
{
if(instr[k]==pstr[0])
{
temp=k;
break;
}
}
newNode->leftchild=Rebulid(pstr+1,instr,temp);
newNode->rightchild=Rebulid(pstr+temp+1,instr+temp+1,len-temp-1);
return newNode;
}
void postorder(Node *roo)
{
if(roo!=NULL)
{
postorder(roo->leftchild);
postorder(roo->rightchild);
cout<<roo->n;
}
else return;
}