给大火看看我无聊的课后作业
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct TreeNode
{
char data;
struct TreeNode* leftchild;
struct TreeNode* rightchild;
}TreeNode, *BitTree;
inline BitTree CreateBitTree1(char *pa, char *la, int p1, int p2, int i1, int i2)
{
int k = 0;
while (i1 + k <= i2 && pa[p1] != la[i1 + k]) k ++;
if (i1 + k > i2) return NULL;
BitTree tree = new TreeNode;
tree -> data = pa[p1];
tree -> leftchild = CreateBitTree1(pa, la, p1 + 1, p1 + k, i1, i1 + k - 1);
tree -> rightchild = CreateBitTree1(pa, la, p1 + k + 1, p2, i1 + k + 1, i2);
return tree;
}
inline BitTree CreateBitTree2(char *pa, char *la, int p1, int p2, int i1, int i2)
{
int k = 0;
while (i1 + k <= i2 && pa[p2] != la[i1 + k]) k ++;
if (i1 + k > i2) return NULL;
BitTree tree = new TreeNode;
tree -> data = pa[p2];
tree -> leftchild = CreateBitTree2(pa, la, p1, p1 + k - 1, i1, i1 + k - 1);
tree -> rightchild = CreateBitTree2(pa, la, p1 + k, p2 - 1, i1 + k + 1, i2);
return tree;
}
inline void PrintPostTravel(BitTree tree)
{
if (tree == NULL) return ;
if (tree -> leftchild) PrintPostTravel(tree -> leftchild);
if (tree -> rightchild) PrintPostTravel(tree -> rightchild);
printf("%c", tree -> data);
}
inline void PrintPreTravel(BitTree tree)
{
if (tree == NULL) return ;
printf("%c", tree -> data);
if (tree -> leftchild) PrintPreTravel(tree -> leftchild);
if (tree -> rightchild) PrintPreTravel(tree -> rightchild);
}
signed main()
{
char pre[20], in[20]; int n;
TreeNode *tree;
printf("输入先序序列\n输入中序序列\n后序序列:");
scanf("%s %s", pre, in);
n = 0;
while (pre[n]) n ++;
tree = CreateBitTree1(pre, in, 0, n - 1, 0, n - 1);
PrintPostTravel(tree);
printf("\n");
printf("输入后序序列\n输入中序序列\n先序序列:");
scanf("%s %s", pre, in);
n = 0;
while (pre[n]) n ++;
tree = CreateBitTree2(pre, in, 0, n - 1, 0, n - 1);
PrintPreTravel(tree);
printf("\n");
return 0;
}
用非递归写就没这么无聊了
刚写完,也还好