#include <iostream>
#include <string.h>
using namespace std;
template<typename Type>
struct Node
{
Type data;
Node<Type> *left;
Node<Type> *right;
Node(Type d = Type()):data(d),left(NULL),right(NULL){}
};
template<typename Type>
class MTree
{
public:
MTree()
{
root = NULL;
}
void Init(const char *s1,const char *s2)
{
int n = strlen(s1);
Init(root,s1,s2,n);
}
void Printf()
{
_Printf(root);
}
private:
void _Printf(Node<Type> *t)
{
if(t!=NULL)
{
cout<<t->data<<"\t";
_Printf(t->left);
_Printf(t->right);
}
}
void Init(Node<Type> *&t,const char *&s1,const char *s2,int n)
{
//根据二叉树的前序跟后续构造二叉树.
int i = 0;
if(*s1==‘\0‘)return;
for(;i<=n;i++)
{
if(*s1==s2[i])
{
break;
}
}
if(i>n)return;
t = new Node<Type>(*s1);
Init(t->left,++s1,s2,i-1);
Init(t->right,s1,s2+i+1,n-i);
}
Node<Type> *root;
};
int main()
{
MTree<char> mt;
char *s1 = new char[7];
char *s2 = new char[7];
strcpy(s1,"ABCDEFG");
strcpy(s2,"CBDAFEG");
mt.Init(s1,s2);
mt.Printf();
return 0;
}
时间: 2024-10-07 05:11:39