给出二叉树的中序遍历序列和后序遍历序列,编程还原该二叉树。
输入:
第1行为二叉树的中序遍历序列
第2行为二叉树的后序遍历序列
输出:
二叉树的按层遍历序列
测试输入 | 期待的输出 | 时间限制 | 内存限制 | 额外进程 | |
---|---|---|---|---|---|
测试用例 1 | 以文本方式显示
| 以文本方式显示
| 1秒 | 64M | 0 |
测试用例 2 | 以文本方式显示
| 以文本方式显示
| 1秒 | 64M | 0 |
测试用例 3 | 以文本方式显示
| 以文本方式显示
| 1秒 | 64M | 0 |
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct TreeNode
{
char data;
struct TreeNode *lchild;
struct TreeNode *rchild;
struct TreeNode *next;
} BiNode, *BiTree;
BiTree CreateTree(char *iorder, char *porder, int L_border, int R_border, int p, int q)
{
char proot = porder[q];
int iroot_postion, rootflag = 0;
for (int i = L_border; i <= R_border; i++)
{
if (iorder[i] == proot)
{
iroot_postion = i;
rootflag = 1;
break;
}
}
if (rootflag == 0)
return NULL;
else
{
BiTree root = (BiTree)malloc(sizeof(BiNode));
root->data = iorder[iroot_postion];
if (iroot_postion == L_border && iroot_postion == R_border)
{
root->lchild = NULL;
root->rchild = NULL;
}
else if (iroot_postion == L_border)
{
root->lchild = NULL;
root->rchild = CreateTree(iorder, porder, L_border + 1, R_border, p, q - 1);
}
else if (iroot_postion == R_border)
{
root->rchild = NULL;
root->lchild = CreateTree(iorder, porder, L_border, R_border - 1, p, q - 1);
}
else
{
root->lchild = CreateTree(iorder, porder, L_border, iroot_postion - 1, p, p + iroot_postion - L_border - 1);
root->rchild = CreateTree(iorder, porder, iroot_postion + 1, R_border, p + iroot_postion - L_border, q - 1);
}
return root;
}
}
void PrintTree(BiTree root)
{
if (root == NULL)
return;
BiTree *queue = (BiTree *)malloc(sizeof(BiTree));
int front = -1, rear = -1;
queue[++rear] = root;
while (front != rear)
{
BiTree temp = queue[++front];
putchar(temp->data);
if (temp->lchild)
queue[++rear] = temp->lchild;
if (temp->rchild)
queue[++rear] = temp->rchild;
}
}
int main()
{
char iorder[100], porder[100];
scanf("%s", iorder);
scanf("%s", porder);
int n = strlen(iorder);
BiTree root = CreateTree(iorder, porder, 0, n - 1, 0, n - 1);
PrintTree(root);
putchar('\n');
return 0;
}