PAT 1127 ZigZagging on a Tree (30)
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. And it is a simple standard routine to print the numbers in level-order. However,if you think the problem is too simple,then you are too naive. This time you are supposed to print the numbers in "zigzagging order" -- that is,starting from the root,print the numbers level-by-level,alternating between left to right and right to left. For example,for the following tree you must output: 1 11 5 8 17 12 20 15. 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 inorder 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,print the zigzagging sequence of the tree in a line. 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: 8 12 11 20 17 1 15 8 5 12 20 17 11 15 8 5 1 Sample Output:
1 #include<iostream> 2 #include<vector> 3 #include<queue> 4 using namespace std; 5 vector<int> in(30),post(30),level1[30],level2[30]; 6 int v[30][2],root; 7 void dfs(int &index,int inl,int inr,int postl,int postr){ 8 int temp=post[postr],i=inl; 9 if(inl>inr) return; 10 index = postr; 11 while(i<=inr && in[i]!=temp) i++; 12 dfs(v[index][0],inl,i-1,postl,postl+(i-inl)-1); 13 dfs(v[index][1],i+1,inr,postl+i-inl,postr-1); 14 } 15 16 void levelOrder(){ 17 queue<int> q1,q2; 18 q1.push(root); 19 int cnt1=0,cnt2=0; 20 while(q1.size() || q2.size()){ 21 int temp,flag1=0,flag2=0; 22 while(q1.size()){ 23 temp=q1.front(); 24 q1.pop(); 25 level1[cnt1].push_back(post[temp]); 26 if(v[temp][0]!=-1) q2.push(v[temp][0]); 27 if(v[temp][1]!=-1) q2.push(v[temp][1]); 28 flag1=1; 29 } 30 if(flag1) cnt1++; 31 while(q2.size()){ 32 temp=q2.front(); 33 q2.pop(); 34 level2[cnt2].push_back(post[temp]); 35 if(v[temp][0]!=-1) q1.push(v[temp][0]); 36 if(v[temp][1]!=-1) q1.push(v[temp][1]); 37 flag2=1; 38 } 39 if(flag2) cnt2++; 40 } 41 } 42 int main(){ 43 int n,i,j; 44 cin>>n; 45 fill(v[0],v[0]+60,-1); 46 for(i=0; i<n; i++) cin>>in[i]; 47 for(i=0; i<n; i++) cin>>post[i]; 48 dfs(root,0,n-1,n-1); 49 levelOrder(); 50 cout<<level1[0][0]; 51 for(i=1; i<n; i++) 52 if(i%2==1) for(j=0; j<level2[i/2].size(); j++) cout<<" "<<level2[i/2][j]; 53 else for(j=level1[i/2].size()-1; j>=0; j--) cout<<" "<<level1[i/2][j]; 54 return 0; 55 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |