程式設計基礎76 已知前序,後序和層序遍歷序列與中序遍歷序列組合得到樹的方法
阿新 • • 發佈:2018-12-04
#include<cstdio> #include<queue> using namespace std; const int max_n = 50; int N = 0; int level[max_n]; int in[max_n]; int post[max_n]; bool flag[max_n] = { false }; struct node { int data; node *lchild; node *rchild; }; node *pre_in(int preL, int preR, int inL, int inR) { if (preL > preR) { return NULL; } node *root = new node; root->data = pre[preL]; int k, num_of_lchild; for (k = 0; in[k] != pre[preL]; k++) { } num_of_lchild = k - inL; root->lchild = pre_in(preL + 1, preL + num_of_lchild, inL, k - 1); root->rchild = pre_in(preL + num_of_lchild + 1, preR, k + 1, inR); return root; } node *level_in() { int index = 0; queue<node*> q; node *root = new node; root->data = level[index]; root->lchild = NULL; root->rchild = NULL; index++; q.push(root); node *temp; int i; while (!q.empty()) { temp = q.front(); q.pop(); for (i = 0; i < N; i++) { if (temp->data == in[i]) { flag[i] = true; break; } } if (flag[i - 1] == false && i > 0) { node *t = new node; t->data = level[index]; t->lchild = NULL; t->rchild = NULL; temp->lchild = t; index++; q.push(t); } if (flag[i + 1] == false && i < N - 1) { node *t = new node; t->data = level[index]; t->lchild = NULL; t->rchild = NULL; temp->rchild = t; index++; q.push(t); } } return root; } node *post_in(int postL, int postR, int inL, int inR) { if (postL > postR) { return NULL; } node *root = new node; root->data = post[postR]; int k; for (k = 0; in[k] != post[postR]; k++) { } int num_of_right = inR - k; root->lchild = post_in(postL, postR - 1 - num_of_right, inL, k - 1); root->rchild = post_in(postR - num_of_right, postR - 1, k + 1, inR); return root; } void pre(node *root) { if (root == NULL) { return; } printf("%d ", root->data); pre(root->lchild); pre(root->rchild); } int main() { node *root; scanf("%d", &N); for (int i = 0; i < N; i++) { scanf("%d", &level[i]); } for (int i = 0; i < N; i++) { scanf("%d", &post[i]); } for (int i = 0; i < N; i++) { scanf("%d", &in[i]); } // root = level_in(); // root = pre_in(0, N - 1, 0, N - 1); // root = post_in(0, N - 1, 0, N - 1); pre(root); return 0; }