标签:include positive roo cas ack enc order lan res
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.
Each input file contains one test case. For each case, the first line gives a positive integer N (≤ 50,000), 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.
For each test case, print in one line the first number of the postorder traversal sequence of the corresponding binary tree.
7
1 2 3 4 5 6 7
2 3 1 5 4 7 6
3
已知中序,前序得后序
输出后序第一个数后就立即剪枝,减少复杂度
1 #include <iostream> 2 #include <vector> 3 using namespace std; 4 int n, num; 5 bool flag = false; 6 vector<int>preOrder, inOrder, postOrder; 7 void travel(int root, int L, int R)//L,R为中序遍历的,root为前序遍历的第一个点 8 { 9 if (L > R || flag) 10 return; 11 int i = L; 12 while (inOrder[i] != preOrder[root])++i; 13 travel(root + 1, L, i - 1);//遍历左子树Order 14 travel(root + 1 + i - L, i + 1, R);//遍历左子树Order 15 //postOrder.push_back(preOrder[root]);//得到完整的后序遍历 16 if (!flag)//输出一个就剪枝 17 { 18 cout << preOrder[root] << endl; 19 flag = true; 20 } 21 } 22 int main() 23 { 24 cin >> n; 25 for (int i = 0; i < n; ++i) 26 { 27 cin >> num; 28 preOrder.push_back(num); 29 } 30 for (int i = 0; i < n; ++i) 31 { 32 cin >> num; 33 inOrder.push_back(num); 34 } 35 travel(0, 0, n - 1); 36 //cout << postOrder[0] << endl; 37 return 0; 38 }
PAT甲级——A1138 Postorder Traversa【25】
标签:include positive roo cas ack enc order lan res
原文地址:https://www.cnblogs.com/zzw1024/p/11494396.html