二叉树遍历 已知中序后序遍历求前序遍历

已知中序、后序遍历求前序遍历的方法和已知前序、中序遍历求后序遍历的方法类似寻找根节点,

然后把中序遍历分成左右两个子树,有如此不断递归。很多文章介绍,不再累述。

#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
const int MAXN = 100;
struct Node {
    char value;
    Node *left_child;
    Node *right_child;
    Node () {
        left_child = right_child = NULL;
    }
};
bool first = true;
void Pre_order(Node *tree) {
    if(first) {
        cout << tree->value;
        first = false;
    } else cout << " " << tree->value;

    if(tree->left_child != NULL) {
        Pre_order(tree->left_child);
    }
    if(tree->right_child != NULL) {
        Pre_order(tree->right_child);
    }
}
Node* build(char pos[], char in[], int n) {
    if(n == 0) return NULL;
    Node *tmp = new Node;
    for(int i = 0; i < n; i++) {
        if(in[i] == pos[n-1]) {
            tmp->value = pos[n-1];
            tmp->left_child = build(pos, in, i);
            tmp->right_child = build(pos+i, in+i+1, n-i-1);
            return tmp;
        }
    }
    return NULL;
}

int main() {
    int n;
    char posorder[MAXN], inorder[MAXN];
    scanf("%d", &n);
    first = false;
    scanf("%s", inorder);
    scanf("%s", posorder);
    Node *tree = build(posorder, inorder, n);
    Pre_order(tree);
    return 0;
}
原文地址:https://www.cnblogs.com/cshg/p/6579696.html