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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

1086 Tree Traversals Again (25 分)【一般 / 建树 树的遍历】

發布時間:2025/3/20 编程问答 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 1086 Tree Traversals Again (25 分)【一般 / 建树 树的遍历】 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.


https://pintia.cn/problem-sets/994805342720868352/problems/994805380754817024
首先要知道的是:

  • 入棧順序就是樹的前序遍歷的順序
  • 出棧順序就是樹的中序遍歷的順序

故問題,就轉換成了根據前序遍歷,中序遍歷的順序建樹的過程。
最后遍歷樹輸出后序遍歷的結果即可。

#include<bits/stdc++.h> using namespace std; vector<int>a,b,ans; stack<int>st; int n; unordered_map<int,int>L,R,S; int build(int l1,int r1,int l2,int r2) {auto root=a[l1];int k=S[root];//找到中序遍歷所對應的位置。if(k>l2) L[root]=build(l1+1,l1+k-l2,l2,k-1);if(k<r2) R[root]=build(l1+k-l2+1,r1,k+1,r2);return root; } void dfs(int root) {if(L.count(root)) dfs(L[root]);//有左兒子if(R.count(root)) dfs(R[root]);//有右兒子ans.push_back(root); } int main(void) {cin>>n;for(int i=0;i<n*2;i++){string op; cin>>op;if(op=="Push"){int x; cin>>x;a.push_back(x);st.push(x);}else{int u=st.top(); st.pop();b.push_back(u);}}for(int i=0;i<b.size();i++) S[b[i]]=i;build(0,n-1,0,n-1);//建樹dfs(a[0]);//遍歷樹for(int i=0;i<ans.size();i++) {if(i) cout<<" ";cout<<ans[i];}return 0; }

總結

以上是生活随笔為你收集整理的1086 Tree Traversals Again (25 分)【一般 / 建树 树的遍历】的全部內容,希望文章能夠幫你解決所遇到的問題。

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