PAT (Advanced Level) Practice 1086 Tree Traversals Again

根據操作寫遞歸就行了,注意一點,data不是從1到n順序來的,所以要自己去獲取push後面的數字,不能簡單的用計數器++。 

#include <iostream>
#include <string>
#include <vector>
#include <stdio.h>
using namespace std;
struct node{
    node* lchild;
    node* rchild;
    int data;
};
vector<int> v;
string op[100];
int index=0,n;
node* createTree(){
    if(index>=2*n) return NULL;

    if(op[index][1]=='u'){//push
        node* root = new node;
        string s = op[index];
        s.erase(0,5);
        int sum=0;
        for(int i=0;i<s.size();i++){
            sum=sum*10 + s[i]-'0';
        }
        root->data=sum;
        index++;
        root->lchild=createTree();
        root->rchild=createTree();
        return root;
    }else{
        index++;
        return NULL;
    }
}
void posttravel(node* root){
    if(root!=NULL){
        posttravel(root->lchild);
        posttravel(root->rchild);
        v.push_back(root->data);
    }
}
int main()
{
    cin>>n;
    getchar();
    for(int i=0;i<2*n;i++){
        getline(cin,op[i]);
    }
    node* root = createTree();
    posttravel(root);
    for(int i=0;i<v.size();i++){
        cout<<v[i];
        if(i!=v.size()-1) cout<<" ";
    }
    return 0;
}

 

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