已知后序遍历和中序遍历求解前序遍历

/**
author : coder_zhang
time : 2014-6-14
**/
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX 100 #define ARRAY_SIZE(array, type) (sizeof(array) / sizeof(type)) typedef struct node { int value; struct node* left; struct node* right; } node; void pre_order(node* root) { node* stack[MAX]; int pos = -1; while (root != NULL || pos != -1) { if (root == NULL) { root = stack[pos--]; } fprintf(stderr, "%c\t", root->value); if (root->right != NULL) { stack[++pos] = root->right; } root = root->left; } fprintf(stderr, "\n"); } int index_char(const char* str, char ch) { int pos = 0; while (*str != '\0' && *str != ch) { ++pos; ++str; } return *str == '\0' ? -1 : pos; } void create_tree(node** root, const char* post_str, const char* in_str, int p_start, int p_end, int i_start, int i_end) { if (p_start <= p_end) { *root = (node*)malloc(sizeof(node)); if (*root == NULL) { fprintf(stderr, "malloc memory failed!\n"); exit(1); } (*root)->value = post_str[p_end]; (*root)->left = (*root)->right = NULL; int pos = index_char(in_str, post_str[p_end]); if (pos != -1) { int dis = pos - i_start; create_tree(&(*root)->left, post_str, in_str, p_start, p_start+dis-1, i_start, i_start+dis-1); create_tree(&(*root)->right, post_str, in_str, p_start+dis, p_end-1, pos+1, i_end); } } } int main(void) { char post_str[MAX]; char in_str[MAX]; fprintf(stderr, "input post str:"); fgets(post_str, MAX, stdin); post_str[strlen(post_str)-1] = '\0'; fprintf(stderr, "input in str:"); fgets(in_str, MAX, stdin); in_str[strlen(in_str)-1] = '\0'; node* root = NULL; create_tree(&root, post_str, in_str, 0, strlen(post_str)-1, 0, strlen(in_str)-1); pre_order(root); return 0; }

 

posted @ 2014-06-14 22:14  coder_zhang1  阅读(410)  评论(0编辑  收藏  举报