4-14 还原二叉树
输入格式:
输入首先给出正整数N(≤50),为树中结点总数。下面两行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区别大小写)的字符串。
输出格式:
输出为一个整数,即该二叉树的高度。
输入样例:
9
ABDFGHIEC
FDHGIBEAC
结尾无空行
输出样例:
5
结尾无空行
#include<stdio.h>
#include<stdlib.h>
char a[10005], b[10005];
typedef struct treenode* tree;
struct treenode {
char data;
tree lchild, rchild;
};
tree creat() {
tree tr = (tree)malloc(sizeof(struct treenode));
tr->lchild = tr->rchild = NULL;
return tr;
}
tree find(int preL, int preR, int inL, int inR) { //后续表达式中子树的最左 最右 中序表达式中搜索的起点 终点
tree head = creat();
head->data = a[preL];
for (int i = inL; i <= inR; i++) {
if (b[i] == a[preL]) {
int numLeft = i - inL;
if (i != inL) //判断是否有左子树;
head->lchild = find(preL + 1, preL + numLeft, inL, i - 1);
if (i != inR) //判断是否有左子树;
head->rchild = find(preL + numLeft + 1, preR, i + 1, inR);
}
}
return head;
}
int getHeight(tree head) { //获取高度函数
if (head == NULL) return 0;
int n;
n = getHeight(head->lchild) > getHeight(head->rchild) ? getHeight(head->lchild) + 1 : getHeight(head->rchild) + 1;
return n;
}
int main() {
int n;
scanf("%d", &n);
getchar(); //消除换行键的'\0'
for (int i = 0; i < n; i++)
scanf("%c", &a[i]);
getchar();
for (int i = 0; i < n; i++)
scanf("%c", &b[i]);
tree head = find(0, n - 1, 0, n - 1);
printf("%d\n", getHeight(head));
return 0;
}