hdu 3999:The order of a Tree

給定一串數字,以二叉排序樹的形式儲存,輸出它的最小字典序序列。


不管怎麼看都是二叉排序樹的先序遍歷,簡單的題。第一次嘗試用類來做,一次就過,好高興(^o^)丿


#include <cstdio>
#include <iostream>
using namespace std;

class node{
private:
    int k;
    bool head;
    node *l,*r;
public:
    node(bool h=0):head(h),k(-1){l=r=NULL;}
    void insert(int x);
    void preorder();
};

void node::insert(int x){
    if(k==-1) k=x;
    else {
        if(x<k){
            if(!l) l=new node;
            l->insert(x);
        }
        else {
            if(!r) r=new node;
            r->insert(x);
        }
    }
}

void node::preorder(){
    if(head) cout<<k;
    else cout<<' '<<k;
    if(l) l->preorder();
    if(r) r->preorder();
}

int n;

int main(){
    while(cin>>n){
        node p(1);
        while(n--){
            int x;
            cin>>x;
            p.insert(x);
        }
        p.preorder();
        cout<<"\n";
    }
    return 0;
}


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