日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【详细注解】1020 Tree Traversals (25 分)

發布時間:2024/2/28 编程问答 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【详细注解】1020 Tree Traversals (25 分) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

立志用最少的代碼做最高效的表達


PAT甲級最優題解——>傳送門


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


題意:給定中序、后序序列,求層序序列。

模板題。 注解已在代碼中標出。 如有疑問請評論區留言~


#include<bits/stdc++.h> using namespace std;struct Node{int data; //值 Node *left, *right; //左節點、右節點 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; //左子樹的節點個數//L1-R1代表中序遍歷左子樹, L2-R2代表后續遍歷左子樹,后續遍歷通過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; }

耗時:


????????????????——做自己的守護神

超強干貨來襲 云風專訪:近40年碼齡,通宵達旦的技術人生

總結

以上是生活随笔為你收集整理的【详细注解】1020 Tree Traversals (25 分)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。