1. 程式人生 > 實用技巧 >由二叉樹的中序層序重建二叉樹

由二叉樹的中序層序重建二叉樹

一定要注意,外部變數【陣列】開的大小,太大了會溢位,太小了提交的時候會溢位,這是一門學問啊

#include <iostream>
#include <vector>
#include <string>
#include <queue>
#include <cstring>

#define MAX 99999
using namespace std;

struct tree
{
    int data;
    tree *left;
    tree *right;

    tree()
    {
        left 
= NULL; right = NULL; } }; tree *root; int layerr[MAX]; int midd[MAX]; int nn; tree *build(int *layer, int *mid, int n) { if (n == 0) return NULL; int Llayer[MAX],Rlayer[MAX]; int Lmid[MAX],Rmid[MAX]; tree *t = new tree(); t->data = layer[0]; int x = 0;
while (layer[0] != mid[x]) x++; //mid int c = 0; for (int i = 0; i < x; i++) { Lmid[c++] = mid[i]; } c=0; for (int i = x+1; i < n; i++) { Rmid[c++] = mid[i]; } //layer int Ll=0,Rl=0; for (int i = 1; i < n; i++) { for (int
k = 0; k < x; k++) { if(layer[i] == mid[k]) Llayer[Ll++] = mid[k]; } } for (int i = 1; i < n; i++) { for (int k = x; k < n; k++) { if(layer[i] == mid[k]) Rlayer[Rl++] = mid[k]; } } t->left = build(Llayer, Lmid, Ll); t->right = build(Rlayer, Rmid, Rl); return t; } void PreOrder(tree *t) { if (t) { cout << t->data << " "; PreOrder(t->left); PreOrder(t->right); } } void PostOrder(tree *t) { if (t) { PostOrder(t->left); PostOrder(t->right); cout << t->data << " "; } } int main() { cin >> nn; for (int i = 0; i < nn; ++i) cin >> layerr[i]; for (int i = 0; i < nn; ++i) cin >> midd[i]; root = build(layerr, midd, nn); PreOrder(root); cout << endl; PostOrder(root); return 0; }