/*给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。
输入格式 :
输入首先给出正整数N(≤50),为树中结点总数。下面两行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区别大小写)的字符串。
输出格式 :
输出为一个整数,即该二叉树的高度。
输入样例 :
9
ABDFGHIEC
FDHGIBEAC
输出样例 :
5*/
/*分析:
先序中的第一个字母把中序分割成两半;中序中的左边为根节点的左子树,右边为根节点的右子树;
不断循环,直到结束。
1.将根节点的值写入;
(根节点的左右儿子信息需要在递归到最后一部分返回)
2.将根节点的左右节点的信息保留在栈中(递归)
3.递归结束条件儿子为空。
/
#include
#define Max 55
using namespace std;
char pre[Max];//先序
char in[Max];//中序
int n;//节点个数
typedef struct Node Tree;
struct Node {
char item;
Tree Left;
Tree Right;
};
Tree findTree(char pre[],char in[],int lenghth) {
//循环结束条件:lenghth0,即当只剩一个字母时,再向下传递时,传递的数组长度为0;
if (lenghth == 0) return NULL;
//pre[]的第一个元素为根节点。即为pre[0]
Tree head = (Tree)malloc(sizeof(struct Node));
head->item = pre[0];
int i = 0;
for (; i < lenghth; i++ ){
if (in[i] == pre[0]) break;
}
head->Left = findTree(pre + 1, in, i);
head->Right = findTree(pre + i + 1, in + i + 1, lenghth-i-1);
return head;
}
int Length(Tree head) {
if (head NULL) return 0; //如果为空树返回0;同时如果树的左节点或者又节点为空;返回0
int L = Length(head->Left);
int R = Length(head->Right);
return L > R ? L + 1 : R + 1;
}
int main() {
cin >> n >> pre >> in;
Tree head = findTree(pre, in, n);
int L = Length(head);
cout << L;
return 0;
}
#include<iostream>
#define Max 55
using namespace std;
char pre[Max];//先序
char in[Max];//中序
int n;//节点个数
typedef struct Node* Tree;
struct Node {
char item;
Tree Left;
Tree Right;
};
Tree findTree(char pre[],char in[],int lenghth) {
//循环结束条件:lenghth==0,即当只剩一个字母时,再向下传递时,传递的数组长度为0;
if (lenghth == 0) return NULL;
//pre[]的第一个元素为根节点。即为pre[0]
Tree head = (Tree)malloc(sizeof(struct Node));
head->item = pre[0];
int i = 0;
for (; i < lenghth; i++) {
if (in[i] == pre[0]) break;
}
head->Left = findTree(pre + 1, in, i);
head->Right = findTree(pre + i + 1, in + i + 1, lenghth-i-1);
return head;
}
int Length(Tree head) {
if (head== NULL) return 0; //如果为空树返回0;同时如果树的左节点或者又节点为空;返回0
int L = Length(head->Left);
int R = Length(head->Right);
return L > R ? L + 1 : R + 1;
}
int main() {
cin >> n >> pre >> in;
Tree head = findTree(pre, in, n);
int L = Length(head);
cout << L;
return 0;
}