【详细注解】1020 Tree Traversals (25 分)
立志用最少的代碼做最高效的表達
PAT甲級最優(yōu)題解——>傳送門
Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order 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 (≤30), the total number of nodes in the binary tree. The second line gives the postorder 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 level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.
Sample Input:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
Sample Output:
4 1 6 3 5 7 2
題意:給定中序、后序序列,求層序序列。
模板題。 注解已在代碼中標出。 如有疑問請評論區(qū)留言~
#include<bits/stdc++.h> using namespace std;struct Node{int data; //值 Node *left, *right; //左節(jié)點、右節(jié)點 Node(int d) : data(d), left(nullptr), right(nullptr) {} }; int postOrder[30], inOrder[30]; //存儲后序遍歷、中序遍歷序列Node* createTree(int L1, int R1, int L2, int R2) {if(L1 > R1) return nullptr;Node* r = new Node(postOrder[R2]);int p = L1;while(inOrder[p] != postOrder[R2]) p++;int cnt = p-L1; //左子樹的節(jié)點個數(shù)//L1-R1代表中序遍歷左子樹, L2-R2代表后續(xù)遍歷左子樹,后續(xù)遍歷通過cnt確定 r->left = createTree(L1, p-1, L2, L2+cnt-1); r->right = createTree(p+1, R1, L2+cnt, R2-1);return r; }void levelOrder(Node* root) {queue<Node*>q;q.push(root);bool output = false;while(!q.empty()) {Node*t = q.front();q.pop();if(output) putchar(' ');printf("%d", t->data);output = true;if(t->left != nullptr) q.push(t->left);if(t->right != nullptr) q.push(t->right); } }int main() {int n; cin >> n;for(int i = 0; i < n; i++) cin >> postOrder[i];for(int i = 0; i < n; i++) cin >> inOrder[i];Node *root = createTree(0, n-1, 0, n-1);levelOrder(root);return 0; }
耗時:
????????????????——做自己的守護神
超強干貨來襲 云風(fēng)專訪:近40年碼齡,通宵達旦的技術(shù)人生總結(jié)
以上是生活随笔為你收集整理的【详细注解】1020 Tree Traversals (25 分)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 1019 General Palindr
- 下一篇: 【分析】1021 Deepest Roo