548 - Tree***

来源:互联网 发布:电子竞技 奥运会 知乎 编辑:程序博客网 时间:2024/05/16 14:42
/*题意:给出中序和后序数据,创建一颗二叉树。再根据从根到叶子的路径长,输出路经最短的那个叶子节点纠错时,自己测试一组数据。效果+1*/#include <iostream>#include <string>#include <cstring>#include <cstdio>#include <sstream>using namespace std;struct Node{Node *lchild,*rchild;int v;Node(){lchild=rchild=NULL;v=0;}};int inorder[10010],postorder[10010];int result,value,min_value;string a,b;int len;int init(){istringstream a_in(a);istringstream b_in(b);int temp;len=0;while(a_in>>temp)inorder[len++]=temp;len=0;while(b_in>>temp)postorder[len++]=temp;return  len;}int getPos(int c,int *t){for(int i=0;i<len;i++)if(c==t[i])return i;return 0;}Node *createTree(int n,int *t1,int *t2){if(n<=0)return NULL;Node *root=new Node;root->v=t2[n-1];int pos=getPos(t2[n-1],t1);root->lchild=createTree(pos,t1,t2);root->rchild=createTree(n-pos-1,t1+pos+1,t2+pos);return root;}void traverse(Node *root){value+=root->v;if(root->lchild==NULL && root->rchild==NULL){if(value<min_value){min_value=value;result=root->v;}//In the case of multiple paths of least value you should pick the one with the least value on the terminal node.//原先没有考虑也通过了,数据太弱了。else if(value==min_value){result=result<root->v?result:root->v;}}if(root->lchild!=NULL){traverse(root->lchild);}if(root->rchild!=NULL){traverse(root->rchild);}value-=root->v;//如果不使用回溯,将value设置成形参也可}int main(){//freopen("data.in","r",stdin);while(getline(cin,a) && getline(cin,b)){int len=init();Node *root=createTree(len,inorder,postorder);min_value=1000000000;value=0;result=0;traverse(root);printf("%d\n",result);}return 0;}