|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include <iostream>
#include <cstring>
#include<math.h>
using namespace std;
struct node {
char data;
node* left;
node* right;
};
typedef node* tree;
int find_(char* inorder, int size, char data) {
for (int i = 0; i < size; i++) {
if (inorder[i] == data)
return i;
}
return -1;
}
node* buildtree(char* postorder, char* inorder, int n) {
if (n <= 0)
return NULL;
char tdata = postorder[n - 1];
int k = find_(inorder, n, tdata);
if(k==-1)
{
return NULL;
}
node* root = new node;
root->data = tdata;
root->left = buildtree(&postorder[0], &inorder[0], k);
root->right = buildtree(&postorder[k], &inorder[k+1], n - k - 1);
return root;
}
int get_height(tree t) {
if (t == NULL)
return -1;
int d1 = get_height(t->left);
int d2 = get_height(t->right);
return max(d1, d2) + 1;
}
void Preorder(tree t) {
if (t == NULL)
return;
cout << t->data;
Preorder(t->left);
Preorder(t->right);
}
int main() {
char postorder[10000];
char inorder[10000];
while (scanf("%s", postorder) != EOF && scanf("%s", inorder) != EOF) {
int n = strlen(inorder);
tree root = buildtree(postorder, inorder, n);
int height = get_height(root);
if(root==NULL) cout<<"INVALID"<<endl;
else
{
cout << height << endl;
Preorder(root);
cout << endl;
}
}
return 0;
}感觉在递归的时候如果k==-1就要返回上一级而不是直接结束函数,导致一些不合法的输入,还会输出一些字符,该如何修改
|
|