给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数N(≤30),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。
输出格式:
在一行中输出该树的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。
输入样例:
1 2 3
| 7 2 3 1 5 7 6 4 1 2 3 4 5 6 7
|
输出样例:
思路:
后中序得到二叉树,再利用队列进行层序遍历。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| #include<iostream> #include<queue> using namespace std; typedef struct Node{ int data; struct Node * lchild; struct Node * rchild;
}*Tree;
Tree postOrder(int post[],int mid[],int len){ if(len==0) return NULL; Tree bt=(Tree)malloc(sizeof(struct Node)); bt->data=post[len-1]; int i=0; for(i=0;i<len;i++){ if(post[len-1]==mid[i]) break; } bt->lchild=postOrder(post,mid,i); bt->rchild=postOrder(post+i,mid+i+1,len-i-1); return bt; } void print(Tree bt){ queue<Tree>q; q.push(bt); int isfir=1; while(!q.empty()){ Tree root = q.front(); if(!isfir) cout<<" "; cout<<q.front()->data; isfir=0; if(root->lchild) q.push(root->lchild); if(root->rchild) q.push(root->rchild); q.pop(); } } int main(){ int n; cin>>n; int mid[n],post[n]; for(int i=0;i<n;i++){ cin>>post[i]; } for(int i=0;i<n;i++){ cin>>mid[i]; } Tree bt = postOrder(post,mid,n); print(bt); }
|