[PAT] A1086 Tree Traversals Again
阿新 • • 發佈:2020-07-15
題目大意
用棧的形式給出一棵二叉樹的建立的順序,求這棵二叉樹的後序遍歷
tips
string用printf輸出:printf(“%s”, str.c_str());
AC程式碼
#define _CRT_SECURE_NO_WARNINGS #include<iostream> #include <cstdio> #include <vector> #include<algorithm> #include<stack> using namespace std; vector<int>pre, in; bool space = false; void postorder(int root, int start, int end) { if (start > end)return; int i = start; while (i < end && in[i] != pre[root])i++; postorder(root + 1, start, i - 1); postorder(root + (i - start) + 1, i + 1, end); if (space == false) { printf("%d", pre[root]); space = true; } else printf(" %d", pre[root]); } int main() { int i, n; scanf("%d", &n); stack<int>st; string op; int number; for (i = 0;i < 2 * n;i++) { cin >> op; if (op == "Push") { scanf("%d", &number); st.push(number); pre.push_back(number); } else {//op=="Pop" in.push_back(st.top()); st.pop(); } } postorder(0, 0, n - 1); return 0; }
另
題目說結點編號1~N,保證了節點值互不相同。
如果在有多個節點的值相同的情況下,之前的程式碼會輸出錯誤的結果,所以修改後的程式碼中添加了key作為索引,前中後序中均儲存索引值,然後用value儲存具體的值。(參考: https://blog.csdn.net/liuchuo/article/details/52181237 )程式碼如下:
#define _CRT_SECURE_NO_WARNINGS #include<iostream> #include <cstdio> #include <vector> #include <map> #include<algorithm> #include<stack> #include <cstring> using namespace std; vector<int> pre, in, post, value; void postorder(int root, int start, int end) { if (start > end) return; int i = start; while (i < end && in[i] != pre[root]) i++; postorder(root + 1, start, i - 1); postorder(root + 1 + i - start, i + 1, end); post.push_back(pre[root]); } int main() { int n; scanf("%d", &n); char str[5]; stack<int> s; int key = 0; while (~scanf("%s", str)) { if (strlen(str) == 4) { int num; scanf("%d", &num); value.push_back(num); pre.push_back(key); s.push(key++); } else { in.push_back(s.top()); s.pop(); } } postorder(0, 0, n - 1); printf("%d", value[post[0]]); for (int i = 1; i < n; i++) printf(" %d", value[post[i]]); return 0; }