POJ 3367 Expression(建立二叉樹)

題目大意:大寫字母會作爲其前兩個字母的父節點,並替換前兩個字符,最終建立二叉樹。輸出時按照從底層到高層,從左子節點到右子節點。

解題方法:用stack建立二叉樹,然後用queue排列輸出順序。

代碼:

#include<cstdio>
#include<iostream>
#include<string>
#include<stack>
#include<queue>
#define N 11000
using namespace std;

struct node{
    char c;
    node * left,*right;
};
queue<node*> que;
stack<node*> stac;
node nodes[10500];
void tree(string str){
    for(int i=0;str[i]!=0;i++){
        if(str[i]>='a'&&str[i]<='z'){
            node * nod=&nodes[i];
            nod->left=NULL;
            nod->right=NULL;
            nod->c=str[i];
            stac.push(nod);
        }
        else{
            node * nod=&nodes[i];
            nod->right=stac.top();stac.pop();
            nod->left=stac.top();stac.pop();
            nod->c=str[i];
            stac.push(nod);
        }
    }
}
int main(){
    int times;

    string str;
    scanf("%d",×);
    for(int i=0;i<times;i++){
           cin>>str;
           tree(str);
           string anw;
           que.push(stac.top());
           while(que.size()!=0){
               node * p=que.front();
               que.pop();
               anw.push_back(p->c);
               if(p->left!=NULL){
                   que.push(p->left);
                   que.push(p->right);
               }
           }
           for(int i=anw.length()-1;i>=0;i--){
               cout<<anw[i];
           }
           cout<<endl;
    }
}


發佈了38 篇原創文章 · 獲贊 19 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章