Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order traversal sequence of the corresponding binary tree.
Each input file contains one test case. For each case, the first line gives a positive integer N (≤), the total number of nodes in the binary tree. The second line gives the postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.
For each test case, print in one line the level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
4 1 6 3 5 7 2
这个推了蛮久的。。。。。不太熟练
//左子树 if(k-l2==0){ tree[root].l = -1;//左子树为空 } else{ buildTree(2*root,l1,l1+k-l2-1,l2,k-1); } //右子树 if(k+1>r2){ tree[root].r = -1;//右子树为空 } else{ buildTree(2*root+1,l1+k-l2,r1-1,k+1,r2); }
AC代码:
#include<bits/stdc++.h> using namespace std; int post[35]; int in[35]; int n; struct node{ int v; int l; int r; }tree[2005]; queue<int>q; void buildTree(int root,int l1,int r1,int l2,int r2){//后序,中序 //cout<<root<<" "<<l1<<"-"<<r1<<" "<<l2<<"-"<<r2<<endl; //先找根节点 tree[root].v = post[r1]; if(l1==r1){ //只有一个节点 tree[root].l = -1; tree[root].r = -1; return; }else{ tree[root].l = 2*root; tree[root].r = 2*root+1; } //找一下根在中序上的位置 int k; for(int i=l2;i<=r2;i++){ if(in[i]==post[r1]){ k=i;//前面k-l2个数就是左子树 break; } } //左子树 if(k-l2==0){ tree[root].l = -1;//左子树为空 } else{ buildTree(2*root,l1,l1+k-l2-1,l2,k-1); } //右子树 if(k+1>r2){ tree[root].r = -1;//右子树为空 } else{ buildTree(2*root+1,l1+k-l2,r1-1,k+1,r2); } } int main(){ int n; cin>>n; for(int i=1;i<=n;i++){ cin>>post[i]; } for(int i=1;i<=n;i++){ cin>>in[i]; } buildTree(1,1,n,1,n); //bfs 层序 while(!q.empty()) q.pop(); q.push(1); while(!q.empty()){ node x=tree[q.front()]; q.pop(); cout<<x.v; if(x.l!=-1){ q.push(x.l); } if(x.r!=-1){ q.push(x.r); } if(!q.empty()){ cout<<" "; } } return 0; }
PAT 甲级 1020 Tree Traversals (25 分)(二叉树已知后序和中序建树求层序)
原文:https://www.cnblogs.com/caiyishuai/p/11333280.html