由二叉树的中序层序重建二叉树
一定要注意,外部变量【数组】开的大小,太大了会溢出,太小了提交的时候会溢出,这是一门学问啊
#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; }
!