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


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