A1020 Tree Traversals(后序+中序 = 二叉树)

 大致题意就是给出二叉树的后序序列和中序序列,要求重建二叉树,然后输出二叉树的层次遍历序列。

这是一道模板题,要先记住大体流程,然后反复练习。

模板一:后序+中序 = 二叉树。

模板二:层次遍历 即BFS。

 1 #include<iostream>
 2 #include<queue>
 3 #include<algorithm>
 4 using namespace std;
 5 const int maxn = 100;
 6 struct Node {
 7     int data;
 8     Node* lchild;
 9     Node* rchild;
10 };
11 
12 int post[maxn],in[maxn];//后序,中序
13 int n;//结点个数
14 
15 //当前二叉树的 后序区间[postL,postR], 中序区间[inL,inR]
16 Node* create(int postL,int postR,int inL,int inR) {
17     //第一步,确定递归边界
18     if(inL > inR) return NULL;
19     //第二步,保存当前根结点
20     Node* root = new Node;
21     root->data = post[postR];
22     //第三步,用根结点划分中序,求出根节点左子树结点的个数
23     int k,leftNum;
24     for(k = inL; k <= inR; ++k)
25         if(in[k] == post[postR]) break;
26     leftNum = k - inL;
27     //第四步,确定左子树的后序、中序, 右子树的后序,中序
28     root->lchild = create(postL,postL+leftNum-1,inL,k-1);
29     root->rchild = create(postL+leftNum,postR-1,k+1,inR);
30     return root;
31 }
32 
33 int num = 0;//已访问结点个数
34 void BFS(Node *root) {//层次遍历
35     queue<Node*> que;//第一步,定义队列,结点入队
36     que.push(root);
37     while(!que.empty()) { //第二步,队列非空
38         Node* top = que.front();//第三步,访问队头元素,并出队
39         que.pop();
40         if(num > 0) printf(" ");
41         cout<<top->data;
42         num++;
43         //第四步,下一层元素入队(左、右孩子入队)
44         if(top->lchild != NULL) que.push(top->lchild);
45         if(top->rchild != NULL) que.push(top->rchild);
46     }
47 }
48 
49 int main() {
50     cin>>n;
51     for(int i = 0; i < n; ++i)
52         cin>>post[i];
53     for(int i = 0; i < n; ++i)
54         cin>>in[i];
55     Node* root = create(0,n-1,0,n-1);//后序+中序重建二叉树
56     BFS(root);    //层次遍历
57     return 0;
58 }

 

posted @ 2020-02-28 21:36  tangq123  阅读(170)  评论(0)    收藏  举报