zoukankan      html  css  js  c++  java
  • 【日常学习】【二叉树遍历】Uva548

    这道题目本身不难,给出后序遍历和中序遍历,求到节点最小路径的叶子,同样长度就输出权值小的叶子。

    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;//notice
    	int 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 inorder
    		read_list(postorder);
    		build(0,n-1,0,n-1);//build a tree
    		best_num=1000000000;
    		dfs(postorder[n-1],0);
    		cout<<best<<endl;;
    	}
    	return 0;
    } 

    五一又要出去培训了。要求相当高。我要抓紧时间学习了。

    ——长风破浪会有时,直挂云帆济沧海

  • 相关阅读:
    12迭代器
    11(2)Vector(向量)
    11(1) LinkList ---链表
    11集合(Collection<E>) Arraylist
    10异常
    乘法计算过程的模拟
    10 Date详解
    详细的OA系统学习
    8 math类
    Java开发中的23种设计模式详解
  • 原文地址:https://www.cnblogs.com/jhcelue/p/6850161.html
Copyright © 2011-2022 走看看