已知二叉树中序,先序,构建树。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <map>
#include <algorithm>
using namespace std;
typedef struct binode{
char key;
binode * left, * right;
}BiNode, * BiTree;
// time complex O(n^2);
int islegeal(const int * out_seri, const int len){
int i = 0, j = 0;
int max_val = -1;
for( i = 0; i < len - 1; i++){
max_val = -1;
for (j = i+1; j < len; j++){
if (out_seri[j] < out_seri[i]){
if (out_seri[j] > max_val){
if (max_val == -1)
max_val = out_seri[j];
else
return 0;
}
else{
max_val = out_seri[j];
}
}
}
}
return 1;
}
int islegeal_order_list(char * Pre_Seri, char * In_Seri){
int i = 0;
int len = 0;
map<char, int> char_map;
map<char,int>::iterator iter;
assert(strlen(Pre_Seri) == strlen(In_Seri));
len = strlen(Pre_Seri);
int * out_seri = new int[len];
while(Pre_Seri[i] != '\0'){
char_map.insert(make_pair(Pre_Seri[i] ,i+1));
i++;
}
i = 0;
while(In_Seri[i] != '\0'){
iter = char_map.find(In_Seri[i]);
if (iter == char_map.end()){
printf("error!\n");
return 0;
}
int loc = iter->second;
out_seri[i] = loc;
i++;
}
for (i = 0; i < len; i++){
printf("%d ",out_seri[i]);
}
printf("\n");
int result = islegeal(out_seri, len);
delete [] out_seri;
return result ;
}
void InOrder_Travese(const BiTree & root){
if(root == NULL){
return;
}
if (root->left != NULL){
InOrder_Travese(root->left);
}
putchar(root->key);
if (root->right != NULL){
InOrder_Travese(root->right);
}
}
BiTree FormTree(char * Pre_Seri, char * In_Seri, const int len){
int i = 0, j = 0;
BiTree left_node, right_node;
int left_tree_len = 0;
int right_tree_len = 0;
char * Right_Pre_Seri = NULL;
char * Right_In_Seri = NULL;
BiTree node = (BiTree)malloc(sizeof(BiNode));
node->key= Pre_Seri[0];
if (len == 1){
node->left = NULL;
node->right = NULL;
return node;
}
if(Pre_Seri[0] != '\0'){
j = 0;
while(j < len){
if (In_Seri[j] == Pre_Seri[0]){
break;
}
j++;
}
left_tree_len = j;
right_tree_len = len - j -1;
Right_Pre_Seri = Pre_Seri + j + 1;
Right_In_Seri = In_Seri + j + 1;
if (left_tree_len == 0){
left_node = NULL;
}
else{
left_node = FormTree(Pre_Seri + 1, In_Seri, left_tree_len);
}
if (right_tree_len == 0){
right_node = NULL;
}
else{
right_node = FormTree(Right_Pre_Seri, Right_In_Seri, right_tree_len);
}
node->left = left_node;
node->right = right_node;
}
return node;
}
int main()
{
char Pre_Seri[] = "ABDHIECFJGK";
char In_Seri[] = "DHIBEAJFCGK";
// char In_Seri[] = "ABCDEFGHIJK";
//char Pre_Seri[] = "ABCDEF";
//char In_Seri[] = "ABCDEF";
int len = strlen(Pre_Seri);
BiTree root;
//int a[] = {5,3,1,4,2};
//printf("%d\n",islegeal(a,5));
assert(strlen(Pre_Seri) == strlen(In_Seri));
int result = islegeal_order_list(Pre_Seri, In_Seri);
printf("%d\n",result);
if (result){
root = FormTree(Pre_Seri, In_Seri, len);
InOrder_Travese(root);
printf("\n");
}
return 0;
}