joj 1329 二叉树

给出中根序列和后根序列求路径值最小的叶节点,各种队,各种栈(话说一开始理解错题了,英语不好的悲哀)

 

#include<iostream>
#include<stack>
#include<queue>
using namespace std;
int mmaaxx;
int k;
void tree(stack<int> s1,stack<int> s2,int m)
{
     if(s1.size()==1&&s2.size()==1)
     {
        if((m+s1.top())<mmaaxx)
        {
           mmaaxx=m+s1.top();
           k=s1.top();
        }
        return ;
     }
     if(s1.size()==0)
        return;
     int t=s2.top();
     s2.pop();
     stack<int> p1,p2,q1,q2;
     while(s1.top()!=t)
     {
         p1.push(s1.top());
         p2.push(s2.top());
         s1.pop();
         s2.pop();
     }    
     s1.pop();
     while(p1.size()!=0)
     {
        q1.push(p1.top());
        q2.push(p2.top());
        p1.pop();
        p2.pop();
     }
     tree(s1,s2,m+t);
     tree(q1,q2,m+t);
}
int main()
{
    int total_case,iii;
    scanf("%d",&total_case);
    getchar();
    for(iii=0;iii<total_case;iii++)
    {
         k=0;
         mmaaxx=10000;
         char str1[500],str2[500],str[500];
         stack<int> s1,s2;
         queue<int> s;
         int a;
         int i=0,j=0;
         gets(str1);
         gets(str2);
         for(i=0;str1[i]!='\0';i++)
         {
            if(str1[i]==32)
            {
               str[j]='\0';
               s1.push(atoi(str));
               j=0;
            }
            else
            {
                str[j]=str1[i];
                j++;
            }
         }
         str[j]='\0';
         s1.push(atoi(str));
         j=0;
         for(i=0;str2[i]!='\0';i++)
         {
            if(str2[i]==32)
            {
               str[j]='\0';
               s2.push(atoi(str));
               j=0;
            }
            else
            {
                str[j]=str2[i];
                j++;
            }
         }
         str[j]='\0';
         s2.push(atoi(str));
         j=0;
         tree(s1,s2,0);
         printf("%d\n",k);
    }
}

 

posted @ 2011-10-28 21:08  DChipNau  阅读(115)  评论(0编辑  收藏  举报