[Daily learning] [binary tree traversal], binary tree traversal

Source: Internet
Author: User

[Daily learning] [binary tree traversal], binary tree traversal

This topic is not difficult in itself. It provides post-order traversal and Middle-order traversal, and finds the leaves with the smallest path of the node. if they are of the same length, the leaves with a smaller weight will be output.

You can't test the vulnerability because it cannot be mounted to the server. It basically follows the ruka code. Directly Add code

//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;} 

On May Day, I have to go out for training again. The requirement is quite high. I have to hurry to study.

-- Sometimes, when the wind breaks through the sea

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.