//  Tree - 二叉树 - 开始
template<typename Data>
class Tree {
    Data data;
    Tree *ll, *rr;
public:
    Tree(Data a) {
        data = a;
        ll = rr = NULL;
    }
    void append(Data a, int (*compare)(Data, Data)) {
        int c = compare(data, a);
        if(c < 0) {
            if(!ll) ll = new Tree(a);
            else ll->append(a, compare);
        }
        if(c > 0) {
            if(!rr) rr = new Tree(a);
            else rr->append(a, compare);
        }
    }
    void preOrder(void (*f)(Data)) {
        f(data);
        if(ll) ll->preOrder(f);
        if(rr) rr->preOrder(f);
    }
    void inOrder(void (*f)(Data)) {
        if(ll) ll->inOrder(f);
        f(data);
        if(rr) rr->inOrder(f);
    }
    void postOrder(void (*f)(Data)) {
        if(ll) ll->postOrder(f);
        if(rr) rr->postOrder(f);
        f(data);
    }
    ~Tree() {
        delete ll;
        delete rr;
    }
};
//  Tree - 二叉树 - 结束

一͛世͛珍͛藏͛
86 声望6 粉丝

« 上一篇
全排列和组合
下一篇 »
二分法查找