PAT-1138. Postorder Traversal (25)
1138. Postorder Traversal (25)
Suppose that all the keys in a binary tree are distinct positive integers. Given the preorder and inorder traversal sequences, you are supposed to output the first number of the postorder 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 (<=50000), the total number of nodes in the binary tree. The second line gives the preorder 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 first number of the postorder traversal sequence of the corresponding binary tree.
Sample Input:7 1 2 3 4 5 6 7 2 3 1 5 4 7 6Sample Output:
3
一棵二叉树前序中序求后序遍历,首先要知道如何手动构建二叉树,然后就是模拟这个过程;建好树之后,知道如何手动求解后序,然后也是模拟这个过程。
说起来非常的简单,需要记住一些细节。
#include <bits/stdc++.h> using namespace std; int N, M, K; int pre[50004], in[50004]; struct Node { Node* left; Node* right; int value; }; Node* buildTree(int* a, int* b, int len) { Node* node = new Node(); node->value = a[0]; //cout<< node->value<< endl; if(len == 0) return NULL; if(len == 1) return node; int k = 0; for(int i = 0; i < len; i++) { if(b[i] == a[0]) { k = i; break; } } node->left = buildTree(a+1, b, k); node->right = buildTree(a+k+1, b+k+1, len-k-1); return node; } int flag = 0; void postOrder(Node* node) { if(node->left) { postOrder(node->left); } if(node->right) { postOrder(node->right); } if(flag == 0){ printf("%d\n", node->value); flag++; } } int main() { cin>> N; for(int i = 0; i < N; i++) { scanf("%d", &pre[i]); } for(int i = 0; i < N; i++) { scanf("%d", &in[i]); } Node* head = buildTree(pre, in, N); postOrder(head); return 0; }