杭电 1710 二叉树

来源:互联网 发布:四川地税网络申报系统 编辑:程序博客网 时间:2024/04/30 07:34

   这道题是给出你二叉树的中序遍历和前序遍历,让求后序遍历。思路很简单,先建立一颗二叉树,之后再后序遍历二叉树即可。题目:

Binary Tree Traversals

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1326    Accepted Submission(s): 633


Problem Description
A binary tree is a finite set of vertices that is either empty or consists of a root r and two disjoint binary trees called the left and right subtrees. There are three most important ways in which the vertices of a binary tree can be systematically traversed or ordered. They are preorder, inorder and postorder. Let T be a binary tree with root r and subtrees T1,T2.

In a preorder traversal of the vertices of T, we visit the root r followed by visiting the vertices of T1 in preorder, then the vertices of T2 in preorder.

In an inorder traversal of the vertices of T, we visit the vertices of T1 in inorder, then the root r, followed by the vertices of T2 in inorder.

In a postorder traversal of the vertices of T, we visit the vertices of T1 in postorder, then the vertices of T2 in postorder and finally we visit r.

Now you are given the preorder sequence and inorder sequence of a certain binary tree. Try to find out its postorder sequence.
 

Input
The input contains several test cases. The first line of each test case contains a single integer n (1<=n<=1000), the number of vertices of the binary tree. Followed by two lines, respectively indicating the preorder sequence and inorder sequence. You can assume they are always correspond to a exclusive binary tree.
 

Output
For each test case print a single line specifying the corresponding postorder sequence.
 

Sample Input
91 2 4 7 3 5 8 9 64 7 2 1 8 5 9 3 6
 

Sample Output
7 4 2 8 9 5 6 3 1
 
ac代码:

#include <iostream>#include <string>#include <cstdio>using namespace std;int pre[1010],in[1010],flag;struct node{int data;node *lchild,*rchild;};void creat_tree(int pre_s,int pre_e,int in_s,int in_e,node *root){root->data=pre[pre_s];int pos=0;for(pos=in_s;pos<=in_e;++pos){  if(pre[pre_s]==in[pos])break;}if(pos==in_s)root->lchild=NULL;else{root->lchild=new node;creat_tree(pre_s+1,pre_s+pos-1,in_s,pos-1,root->lchild);}if(pos==in_e)root->rchild=NULL;else{root->rchild=new node;creat_tree(pre_s+pos+1-in_s,pre_e,pos+1,in_e,root->rchild);}}void postorder(node *root){if(root!=NULL){postorder(root->lchild);postorder(root->rchild);if(flag)printf(" ");printf("%d",root->data);flag=1;}}int main(){//freopen("1.txt","r",stdin);  int n;  while(~scanf("%d",&n)){    for(int i=1;i<=n;++i)scanf("%d",&pre[i]);for(int i=1;i<=n;++i)scanf("%d",&in[i]);node *root=new node;creat_tree(1,n,1,n,root);//cout<<"ss"<<endl;flag=0;postorder(root);printf("\n");  }  return 0;}


原创粉丝点击