已知二查树前序遍历和中序遍历求解后序遍历算法实现
/** 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 post_order(node* root) { node* stack[MAX]; int status[MAX]; int pos = -1; while (root != NULL) { stack[++pos] = root; status[pos] = 0; root = root->left; } while (pos != -1) { root = stack[pos]; if (root->right == NULL || status[pos] == 1) { --pos; fprintf(stderr, "%c\t", root->value); } else { status[pos] = 1; root = root->right; while (root != NULL) { stack[++pos] = root; status[pos] = 0; root = root->left; } } } fprintf(stderr, "\n"); } /* 非递归前序遍历 */ void pre_order_view(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"); } void pre_order_view_1(node* root) { if (root != NULL) { fprintf(stderr, "%c\n", root->value); pre_order_view_1(root->left); pre_order_view_1(root->right); } } 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** p, char* pre_order, char* in_order, int p_start, int p_end, int i_start, int i_end) { if (p_start <= p_end) { *p = (node*)malloc(sizeof(node)); if (*p == NULL) { fprintf(stderr, "malloc memory failed!\n"); exit(1); } (*p)->value = pre_order[p_start]; (*p)->left = (*p)->right = NULL; int pos = index_char(in_order, pre_order[p_start]); if (pos != -1) { int dis = pos - i_start; create_tree(&(*p)->left, pre_order, in_order, p_start+1, p_start+dis, i_start, i_start+dis-1); create_tree(&(*p)->right, pre_order, in_order, p_start+dis+1, p_end, pos+1, i_end); } } } int main(void) { char pre_order[MAX]; char in_order[MAX]; fprintf(stderr, "input pre order string:"); fgets(pre_order, MAX, stdin); pre_order[strlen(pre_order)-1] = '\0'; fprintf(stderr, "input in order string:"); fgets(in_order, MAX, stdin); in_order[strlen(in_order)-1] = '\0'; node* root = NULL; create_tree(&root, pre_order, in_order, 0, strlen(pre_order)-1, 0, strlen(in_order)-1); post_order(root); return 0; }