点击打开题目链接
感觉用串2建树好理解些
1:串1建树
#include <bits/stdc++.h>
using namespace std;
struct node
{
char data;
node *right, *left;
};
int lenth;
char str1[60], str2[60];
node *creat();
void Postorder(node *root);//后序遍历
void levelorder(node *root);//层次遍历
node *build(int low, int high, int _begin);//还原二叉树
int main()
{
int k;
while(cin >> k)
{
while(k --)
{
scanf("%s", str1);
scanf("%s", str2);
lenth = strlen(str2);
node *root = build(0,lenth-1, 0);
Postorder(root);
cout << endl;
levelorder(root);
cout << endl;
}
}
return 0;
}
node *creat()
{
node *root = new node;
root -> left = NULL;
root -> right = NULL;
return root;
}
void Postorder(node *root)
{
if(root)
{
Postorder(root -> left);
Postorder(root -> right);
cout << root -> data;
}
}
node *build(int low, int high, int _begin)
{
int flag;
if(low > high)
return NULL;
node *root = creat();
root -> data = str1[_begin];
for(int i = low; i <= high; i++)
{
if(str1[_begin] == str2[i])
{
flag = i;
break;
}
}
root -> left = build(low, flag-1, _begin+1);
root -> right = build(flag+1,high,_begin+flag+1-low);
return root;
}
void levelorder(node *root)
{
queue<node *>Q;
Q.push(root);
node *tmp;
while(!Q.empty())
{
tmp = Q.front();
Q.pop();
cout << tmp -> data;
if(tmp -> left) Q.push(tmp -> left);
if(tmp -> right) Q.push(tmp -> right);
}
}
2:将串2建树
#include <bits/stdc++.h>
using namespace std;
struct Treenode
{
char data;
Treenode *lchild, *rchild;
};
int k, num;
char str1[60], str2[60];
void levelorder(Treenode *root);
void Postorder(Treenode *root);
Treenode *Insert()
{
Treenode *root = new Treenode;
root -> lchild = root -> rchild = NULL;
return root;
}
Treenode *creat(int low, int high)
{
if(low > high) return NULL;
int flag;
for(int i = low; i <= high; i++)
{
if(str1[k] == str2[i])
{
flag = i;
break;
}
}
k++;
Treenode *root = Insert();
root -> data = str2[flag];
root -> lchild = creat(low, flag-1);
root -> rchild = creat(flag+1,high);
return root;
}
int main()
{
int n;
while(cin >> n)
{
while(n --)
{
k = 0;
scanf("%s", str1);
scanf("%s", str2);
Treenode *root = creat(0, strlen(str2)-1);
Postorder(root);
cout << endl;
levelorder(root);
cout << endl;
}
}
return 0;
}
void Postorder(Treenode *root)
{
if(root)
{
Postorder(root -> lchild);
Postorder(root -> rchild);
cout << root -> data;
}
}
void levelorder(Treenode *root)
{
queue<Treenode *> Q;
Q.push(root);
while(!Q.empty())
{
Treenode *tp = Q.front();
cout << tp -> data;
Q.pop();
if(tp -> lchild) Q.push(tp -> lchild);
if(tp -> rchild) Q.push(tp -> rchild);
}
}