1119. Pre- and Post-order Traversals

来源:互联网 发布:k均值聚类算法matlab 编辑:程序博客网 时间:2024/05/17 01:09

1119. Pre- and Post-order Traversals (30)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Special
作者
CHEN, Yue

Suppose that all the keys in a binary tree are distinct positive integers. A unique binary tree can be determined by a given pair of postorder and inorder traversal sequences, or preorder and inorder traversal sequences. However, if only the postorder and preorder traversal sequences are given, the corresponding tree may no longer be unique.

Now given a pair of postorder and preorder traversal sequences, you are supposed to output the corresponding inorder traversal sequence of the tree. If the tree is not unique, simply output any one of them.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (<=30), the total number of nodes in the binary tree. The second line gives the preorder sequence and the third line gives the postorder sequence. All the numbers in a line are separated by a space.

Output Specification:

For each test case, first printf in a line "Yes" if the tree is unique, or "No" if not. Then print in the next line the inorder traversal sequence of the corresponding binary tree. If the solution is not unique, any answer would do. It is guaranteed that at least one solution exists. 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.

Sample Input 1:
71 2 3 4 6 7 52 6 7 4 5 3 1
Sample Output 1:
Yes2 1 6 4 7 3 5
Sample Input 2:
41 2 3 42 4 3 1
Sample Output 2:
No2 1 3 4

老有乱码啊,改来改去。

前序列中第二个元素为左子树的树根,找到后序列中对应的下标,递归得到一个解。

后序列中倒数二个元素为右子树的树根,找到前序列中对应的下标,递归得到一个解。

注意下标对齐。


#include<iostream>#include<vector>using namespace std;vector<int>a;vector<int>b;vector<int>ansa;vector<int>ansb;void builda(int al,int ar,int bl,int br){int idx;for(int i=al;i<=ar;i++)if(a[i]==b[br-1])idx=i;if(al+1<idx-1)builda(al+1,idx-1,bl,bl+idx-2-al);else if(al+1==idx-1)ansa.push_back(a[al+1]);ansa.push_back(a[al]);if(idx<ar)builda(idx,ar,br-1-ar+idx,br-1);else if(idx==ar)ansa.push_back(a[idx]);}void buildb(int al,int ar,int bl,int br){int idx;for(int i=bl;i<=br;i++)if(a[al+1]==b[i])idx=i;if(bl<idx)buildb(al+1,al+1+idx-bl,bl,idx);else if(bl==idx)ansb.push_back(b[bl]);ansb.push_back(b[br]);if(idx+1<br-1)buildb(ar-br+idx+2,ar,idx+1,br-1);else if(idx+1==br-1)ansb.push_back(b[idx+1]);}int main(){int n;cin>>n;for(int i=0;i<n;i++){int num;cin>>num;a.push_back(num);}for(int i=0;i<n;i++){int num;cin>>num;b.push_back(num);}if(n==1){cout<<"Yes"<<endl;cout<<a[0]<<endl;return 0;}builda(0,n-1,0,n-1);buildb(0,n-1,0,n-1);if(ansb==ansa)cout<<"Yes"<<endl;elsecout<<"No"<<endl;cout<<ansa[0];for(int i=1;i<ansa.size();i++)cout<<" "<<ansa[i];cout<<endl;return 0;}


0 0
原创粉丝点击