#include <iostream>
#include <string.h>
#include <algorithm>
#include <string>
#include <stdio.h>
#include <math.h>
#include <map>
#include <queue>
#include <vector>
#include <stack>
using namespace std;
struct Node {
Node *lchild;
Node *rchild;
char c;
}Tree[50];
int loc;
Node *create(){
Tree[loc].lchild = Tree[loc].rchild = NULL;
return &Tree[loc++];
}
char str1[30], str2[30];
void postOrder(Node *T){
if (T->lchild!=NULL) {
postOrder(T->lchild);
}
if (T->rchild!=NULL) {
postOrder(T->rchild);
}
printf("%c", T->c);
}
void preOrder(Node *T){
printf("%c", T->c);
if (T->lchild!=NULL) {
postOrder(T->lchild);
}
if (T->rchild!=NULL) {
postOrder(T->rchild);
}
}
void inOrder(Node *T){
if (T->lchild!=NULL) {
postOrder(T->lchild);
}
printf("%c", T->c);
if (T->rchild!=NULL) {
postOrder(T->rchild);
}
}
Node *build(int s1, int e1, int s2, int e2){
Node *ret = create();//树节点建立空间
ret->c = str1[s1];//该结点字符为前序遍历第一个
int rootIdx;//根的序号
for (int i = s2; i <= e2; i++) {
if (str2[i] == str1[s1]) {
rootIdx = i;
break;
}
}
if (rootIdx!=s2) {//左子树不为空
ret->lchild=build(s1+1, s1+(rootIdx-s2), s2, rootIdx-1);
}
if (rootIdx!=e2) {//右子树不为空
ret->rchild=build(s1+(rootIdx-s2)+1, e1, rootIdx+1, e2);
}
return ret;
}
int main()
{
while (scanf("%s",str1)!=EOF) {
scanf("%s",str2);
loc = 0;
int L1 = strlen(str1);
int L2 = strlen(str2);
Node *T = build(0, L1-1, 0, L2-1);
postOrder(T);
printf("\n");
}
return 0;
}
给定前序、中序遍历,输出后序遍历
最新推荐文章于 2022-06-23 21:41:51 发布