二叉树已知 先序中序求后序 和 已知后序中序求先序

简单易忘~~~

已知先序中序求后序:

/*
    已知先序和中序 求后序
 */

#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;

#define maxn 1010

int pre[maxn], in[maxn], post[maxn];
int n;
int cnt;

int ask_root(int len, int root_num, int in[]) { //在当前的子树立找根节点
    for (int i=0; i<len; ++i) {
        if (in[i] == root_num)
            return i;
    }
    return -1;
}

void askPost(int len, int pre[], int in[]) { // 当前先序和中序序列的长度
    int root_id = ask_root(len, pre[0], in);
    if (root_id < 0) return;
    askPost(root_id, pre+1, in); // 递归到当前根节点的左子树
    askPost(len-root_id-1, pre+root_id+1, in+root_id+1); // 递归到当前根节点的右子树
    post[cnt++] = pre[0]; // 递归完左子树和右子树之后 剩下了最左的叶子结点 加入后序序列中
}

int main() {
    while(cin >> n) {
         cnt = 0;
         for (int i=0; i<n; ++i) { // 输入先序序列
            cin >> pre[i];
         }
         for (int i=0; i<n; ++i) { // 输入中序序列
            cin >> in[i];
         }

         askPost(n, pre, in); //

         for (int i=0; i<n; ++i) {
            cout << post[i] << endl;
         }
    }
    return 0;
}

  

已知中序后序求先序:

/*
 已知二叉树的中序和后序 求其先序
 */

#include <stdio.h>
#include <string.h>
#include <iostream>
#define maxn 1010
using namespace std;

int pre[maxn], in[maxn], post[maxn];
int n;
int cnt;

int ask_root(int len, int root, int in[]) {
    for (int i=0; i<len; ++i) {
        if (in[i] == root)
            return i;
    }
    return -1;
}

void askPre(int len, int in[], int post[]) {
    int root_id = ask_root(len, post[len-1], in);

   // cout << root_id << "===
";
    if (root_id == -1) return;
    pre[cnt++] = post[len-1]; // 将当前根节点加入到先序序列中
    askPre(root_id, in, post); // 递归到左子树
    askPre(len-root_id-1, in+root_id+1, post+root_id); //递归到右子树
}


int main() {
    while(cin >> n) {
        cnt = 0;
        for (int i=0; i<n; ++i) {
            cin >> in[i]; // 输入中序
        }
        for (int i=0; i<n; ++i) {
            cin >> post[i]; // 输入后序
        }

        askPre(n, in, post);

        for (int i=0; i<n; ++i) {
            cout << pre[i] << endl;
        }
    }
    return 0;
}

  

原文地址:https://www.cnblogs.com/icode-girl/p/5289167.html