代码随想录二叉树23
#include<iostream>
#include<string>
using namespace std;
//二叉树节点
struct treeNode {
char val;
struct treeNode* left;
struct treeNode* right;
};
//根据先序遍历和中序遍历构造二叉树
treeNode* constructTree(string pre, string mid) {
if (pre.length() == 0) return NULL;
if (pre.length() == 1) { //此为叶节点
struct treeNode* root = new treeNode();
root->val = pre[0];
root->left = NULL;
root->right = NULL;
return root;
}
struct treeNode* root = new treeNode();
root->val = pre[0];
int position = mid.find(pre[0]);
root->left = constructTree(pre.substr(1, position), mid.substr(0, position)); //构建左子树
root->right = constructTree(pre.substr(position + 1), mid.substr(position + 1)); //构建右子树
return root;
}
//利用后序遍历求树的高度
int getHigh(treeNode* root) {
if (root == NULL) return 0;
int leftHigh = getHigh(root->left); //左子树高度
int rightHigh = getHigh(root->right); //右子树高度
int high = 1 + max(leftHigh, rightHigh); //树高
return high;
}
int main() {
int n,high;
string pre, mid;
while (cin >> n) {
if (n <= 0 || n > 50) break;
getchar(); //吸收回车
getline(cin, pre); //获取先序遍历序列
getline(cin, mid); //获取中序遍历序列
treeNode* root = constructTree(pre, mid);
high = getHigh(root);
cout << high << endl;
}
return 0;
}