【日常學習】【二叉樹遍曆】,二叉樹遍

來源:互聯網
上載者:User

【日常學習】【二叉樹遍曆】,二叉樹遍

這道題目本身不難,給出後序遍曆和中序遍曆,求到節點最小路徑的葉子,相同長度就輸出權值小的葉子。

Uva上不去了,沒法測。基本上是按照ruka的代碼來的。直接上代碼

//Uva548 Tree#include<iostream>#include<algorithm>#include<string>#include<sstream>#include<cctype>using namespace std;const int maxv=10000+10;int inorder[maxv],postorder[maxv],l[maxv],r[maxv];int n;int best,best_num;bool read_list(int *a){string line;if (!getline(cin,line)) return false;stringstream ss(line);n=0;int x;while (ss>>x) a[n++]=x;return n>0;}int build(int l1,int r1,int l2,int r2){if (l1>r1) return 0;//noticeint root=postorder[r2];int p=0;while (inorder[p]!=root) p++;int cnt=p-l1;l[root]=build(l1,p-1,l2,l2+cnt-1);r[root]=build(p+1,r1,l2+cnt,r2-1);return root;}void dfs(int now,int sum){sum+=now;if ((!l[now])&&(!r[now])){if ((sum<best_num)||((sum==best_num)&&(now<best))){best=now;best_num=sum;}}if (l[now]) dfs(l[now],sum);if (r[now]) dfs(r[now],sum);} int main(){freopen("1.txt","r",stdin);freopen("2.txt","w",stdout);while (read_list(inorder)){//every time you read an inorderread_list(postorder);build(0,n-1,0,n-1);//build a treebest_num=1000000000;dfs(postorder[n-1],0);cout<<best<<endl;;}return 0;} 

五一又要出去培訓了,要求相當高,我要抓緊時間學習了。

——長風破浪會有時,直掛雲帆濟滄海

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.