http://acm.hdu.edu.cn/showproblem.php?pid=1710
题意:给二叉树的先序遍历和中序遍历,确定后序遍历
解法:复习专业课找的一题,根据先序遍历和中序遍历建树,再对树做后序遍历
#include <iostream> #include <cstdio> using namespace std; struct Tree { Tree *lc, *rc; int data; }; Tree *Create(int *preorder, int *inorder, int n) { for(int i = 0; i < n; i++) { if(preorder[0] == inorder[i]) { Tree *node = (Tree*)malloc(sizeof(Tree)); node -> data = preorder[0]; node -> lc = Create(preorder+1, inorder, i); node -> rc = Create(preorder+i+1, inorder+i+1, n-i-1); return node; } } return NULL; } int rt; void PostOrder(Tree *root) { if(root != NULL) { PostOrder(root -> lc); PostOrder(root -> rc); if(root -> data == rt) printf("%d\n", root->data); else printf("%d ", root->data); } } Tree *root; int preorder[1005], inorder[1005]; int main() { int n; while(~scanf("%d", &n)) { for(int i = 0; i < n; i++) scanf("%d", &preorder[i]); for(int i = 0; i < n; i++) scanf("%d", &inorder[i]); root = NULL; rt = preorder[0]; root = Create(preorder, inorder, n); PostOrder(root); } return 0; }