给定非空二叉树的中根序列和后根序列,请编写程序创建该二叉树,计算其高度和先根序列,最后删除该二叉树;如给定的中根和后根序列不合法,则亦能识别
输入格式:
输入包含多组数据(不超过10组),每组为两行字符串,第一行表示某二叉树的后根序列,第二行表示其中根序列。结点的值均为A-Z的大写字母,故二叉树结点个数不超过26,且保证输入的两个序列都是结点的全排列,但不一定是合法的中根和后根序列。输入保证不是空二叉树。
输出格式:
对于每组数据,如果输入的序列不合法(不是同一棵树的中根序列和后根序列),则输出INVALID;若输入序列合法,输出为两行,第一行为一个整数,表示该二叉树的高度,第二行为一个字符串,表示该二叉树的先根序列。
输入样例:
CEFDBHGA
CBEDFAGH
CBEDFAGH
CEFDBHGA
BCA
CAB
输出样例:
3
ABCDEFGH
INVALID
INVALID
#include <string.h>
#include <stdio.h>
struct Tree {
char data;
Tree* lchild = NULL;
Tree* rchild = NULL;
};
char Postorder[100];
char Inorder[100];
int judge = 1;
int Depth(Tree* t) {
if (t == NULL) return -1;
int m = Depth(t->lchild);
int n = Depth(t->rchild);
if (m > n) return m + 1;
return n + 1;
}
void Preorder(Tree* t) {
if (t == NULL) return;
printf("%c",t->data);
Preorder(t->lchild);
Preorder(t->rchild);
}
void Build(Tree*& t, int len, int pos, int ins)
{
int i = 0;
int flag = 0;
int ine= ins + len;
int poe = pos + len;
for (i= ins; i < ine; i++)
if (Inorder[i] == Postorder[poe - 1]) {
flag = 1;
break;
}
int leftlen = i - ins;
int rightlen = len - i- 1 + ins;
if (flag) {
t = new Tree;
t->data= Inorder[i];
if (leftlen > 0)
Build(t->lchild, leftlen, pos, ins);
if (rightlen > 0)
Build(t->rchild, rightlen, pos + i - ins, i + 1);
}
else
judge= 0;
}
void deleteTree(Tree *root)
{
while (root)
{
deleteTree(root->lchild);
deleteTree(root->rchild);
delete[] root;
root = NULL;
}
}
int main()
{
while(scanf("%s%s", Postorder,Inorder)){
int inlen = strlen(Inorder);
Tree* T;
T = new Tree;
Build(T, inlen, 0, 0);
if (judge == 0) printf("INVALID\n");
else {
printf("%d\n",Depth(T));
Preorder(T);
deleteTree(T);
}
}
return 0;
}
为什么我的运行结果是
CEFDBHGA
CBEDFAGH
3
ABCDEFGHCBEDFAGH
CEFDBHGA
INVALID
BCA
CAB
INVALID
求指导
#include <cstring>
#include <stdio.h>
struct Tree {
char item;
Tree* L = NULL;
Tree* R = NULL;
};
char postorder[30];
char inorder[30];
int istree = 1;
int high(Tree* t) {
if (t == NULL) return -1;
int leftvalue = high(t->L);
int rightvalue = high(t->R);
if (leftvalue > rightvalue) return leftvalue + 1;
return rightvalue + 1;
}
void preorder_travel(Tree* t) {
if (t == NULL) return;
scanf("%c",t->item);
preorder_travel(t->L);
preorder_travel(t->R);
}
void creattree(Tree*& t, int len, int poststart, int instart)
{
int pos = 0;
int flag = 0;
int inend = instart + len;
int postend = poststart + len;
for (pos = instart; pos < inend; pos++)
if (inorder[pos] == postorder[postend - 1]) {
flag = 1;
break;
}
int leftlen = pos - instart;
int rightlen = len - pos - 1 + instart;
if (flag) {
t = new Tree;
t->item = inorder[pos];
if (leftlen > 0)
creattree(t->L, leftlen, poststart, instart);
if (rightlen > 0)
creattree(t->R, rightlen, poststart + pos - instart, pos + 1);
}
else
istree = 0;
}
int main()
{
while(scanf("%s%s", postorder,inorder)){
int inlen = strlen(inorder);
Tree* root;
root = new Tree;
creattree(root, inlen, 0, 0);
if (istree == 0) printf("INVALID\n");
else {
printf("%d\n",high(root));
}
}
return 0;
}