zoukankan      html  css  js  c++  java
  • 已知后序遍历和中序遍历求解前序遍历

    /**
    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 ", root->value); if (root->right != NULL) { stack[++pos] = root->right; } root = root->left; } fprintf(stderr, " "); } int index_char(const char* str, char ch) { int pos = 0; while (*str != '' && *str != ch) { ++pos; ++str; } return *str == '' ? -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! "); 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] = ''; fprintf(stderr, "input in str:"); fgets(in_str, MAX, stdin); in_str[strlen(in_str)-1] = ''; 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; }
  • 相关阅读:
    什么是经验
    Linux驱动开启调试信息
    insecticide|contradictions| at large|delay doing|
    timber|stain|compensate|
    whip|resist|patch|intimate|
    chop|divorce|harsh|mutual|compel|
    crack|erosion|strip|
    stack|session|fuss|anniversary
    abrupt|promising
    nevertheless|magnificent |prosperous|
  • 原文地址:https://www.cnblogs.com/coder-zhang/p/3788774.html
Copyright © 2011-2022 走看看