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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章