HDU1710 二叉樹的前、中、後遍歷
阿新 • • 發佈:2019-01-31
Binary Tree Traversals
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 4438 Accepted Submission(s): 2025
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 9 1 2 4 7 3 5 8 9 6 4 7 2 1 8 5 9 3 6
Sample Output 7 4 2 8 9 5 6 3 1由二叉樹的前序遍歷和中序遍歷,求後序遍歷
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <algorithm> using namespace std; int pre[1100],mid[1100],n; typedef struct Node{ int v; struct Node *left,*right; }node; node* root; node* newNode(int x){ node* u=(node*)malloc(sizeof(node)); u->left=u->right=NULL; u->v=x; return u; } node* creat(int *pre,int l1,int *mid,int l2){ int i,j,k; for(i=0;i<l2;i++) if(pre[0]==mid[i]) break; node* u=newNode(mid[i]); if(i>0) u->left=creat(pre+1,i,mid,i); //重點理解這兩個if就好了 if(i<l2-1) u->right=creat(pre+i+1,l2-i-1,mid+i+1,l2-i-1); return u; } void remove_tree(node* u){ if(u==NULL) return ; remove_tree(u->left); remove_tree(u->right); delete u; } int f; void print(node* u){ if(u==NULL) return ; print(u->left); print(u->right); if(f) printf(" "); f=1; printf("%d",u->v); } int main() { int i,j,n; while(scanf("%d",&n)!=EOF){ for(i=0;i<n;i++) scanf("%d",&pre[i]); for(i=0;i<n;i++) scanf("%d",&mid[i]); remove_tree(root); root=creat(pre,n,mid,n); f=0; print(root); printf("\n"); } return 0; }
注意要養成釋放空間的好習慣!POJ2255和這個題基本一樣