PAT Advance 1020
题目:
1020. Tree Traversals (25)
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.
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 postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.
Output Specification:
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.
Sample Input:7 2 3 1 5 7 6 4 1 2 3 4 5 6 7Sample Output:
4 1 6 3 5 7 2
注意点:
代码中红色代码尤其需要注意,不设置为空的话会出错。
程序:
#include<iostream>
#include<queue>
using namespace std;
typedef struct _Node
{
int num;
struct _Node *lchild;
struct _Node *rchild;
}Node, *PNode;
int t1[1001],t2[1001];
int n;
int getPosition(int a){
int i;
for(i=1;i<=n;i++)
if(a == t2[i])
return i;
}
void createTree(PNode &node, int i, int j, int len){
if(len<=0){
return ;
}
node = new Node;
node->num = t1[i];
node->lchild = NULL;
node->rchild = NULL;
int m = getPosition(t1[i]);
createTree(node->lchild,i-len+m-j,j,m-j);//m-j:左子树len,len-1-(m-j):右子树len
createTree(node->rchild,i-1,m+1,len-1-m+j);
}
void PreTravelTree(PNode pn) //前序递归遍历
{
if(pn){
cout<<pn->num<<" "<<endl;
PreTravelTree(pn->lchild);
PreTravelTree(pn->rchild);
}
}
int main()
{
int i;
int r[100];
queue<PNode> q;
cin>>n;
for(i=1;i<=n;i++)
cin>>t1[i];
for(i=1;i<=n;i++)
cin>>t2[i];
PNode root = NULL,temp;
createTree(root,n,1,n);
q.push(root);
i=0;
while(!q.empty()){
temp = q.front();
q.pop();
r[i] = temp->num;
i++;
if(temp->lchild!=NULL)
q.push(temp->lchild);
if(temp->rchild!=NULL)
q.push(temp->rchild);
}
cout<<r[0];
for(i=1;i<n;i++)
cout<<" "<<r[i];
cout<<endl;
return 0;
}