二叉树后序遍历迭代器(仅支持++)

数据结构作业,昨天康大佬()优化了一下觉得不错,贴上来,供测试使用

#include 
#include 
using namespace std;

template <class Type> struct BTNode {
    BTNode *left;
    Type data;
    BTNode *right;
    BTNode(Type x) {
        data = x;
        left = right = NULL;
    }
};

template <class Type> class PostOrder;

template <class Type> class BinaryTree {
private:
    BTNode *root;
    friend class PostOrder;
public:
    BinaryTree(BTNode*t) { root = t; }
};

//Base class for BT Iterator
template <class Type> class TreeIterator {
protected:
    const BinaryTree  & T; //BT
    const BTNode *current;
public:
    TreeIterator(const BinaryTree  & BT)
        : T(BT), current(NULL) { }
    virtual ~TreeIterator() { }
    virtual void First() = 0;
    virtual void operator ++ () = 0;
    operator bool() { return current != NULL; }
    const Type operator()()const {
        if (current)
            return current->data;
        return (Type)0;
    }
};

template <class Type> struct StkNode {
    //Stack node definition
    const BTNode  *Node;  //Node Address
    int PopTime;                                        //Counter
    StkNode(const BTNode  *N = NULL) : Node(N), PopTime(0) { }
};

template <class Type> class PostOrder : public TreeIterator  {
    bool renew;
public:
    PostOrder(const BinaryTree  & BT) :TreeIterator(BT) { renew = false; }
    ~PostOrder() { }
    void First();
    //Seek to the first node in postorder traversal
    void operator ++ ();
    //Seek to the successor
protected:
    stack> st;     //Active record stack
};

template <class Type>
void PostOrder::First() {
    current = T.root;
    while (!st.empty()) {
        st.pop();
    }
    renew = true;
    operator++();
}

template <class Type>
void PostOrder::operator ++() {
    if (!renew && current == T.root && st.empty()) {
        current = NULL;
        return;
    }
    renew = false;
    const BTNode *p = current;
    StkNode w;
    do {
        // Here, you must add necessary statements to set pointer current to the right posotion
        if (st.empty() || (st.top().Node->left != p && st.top().Node->right != current))
            while (p) {
                st.push(StkNode(p));
                p = p->left;
            }
        w = st.top();
        st.pop();
        if (++w.PopTime == 2) {
            current = w.Node;
            return;
        }
        st.push(w);
        if (w.Node->right) {
            p = w.Node->right;
        }
    } while (true);
}

int main() {
    BTNode<int> *p = new BTNode<int>(6);
    p->left = new BTNode<int>(4);
    p->right = new BTNode<int>(10);
    p->left->left = new BTNode<int>(2);
    p->right->left = new BTNode<int>(8);
    p->right->right = new BTNode<int>(12);
    BinaryTree<int> T(p);
    PostOrder<int> it(T);
    for (it.First(); it; ++it) {
        std::cout << it() << std::endl;
    }

    system("pause");
    return 0;
}

你可能感兴趣的:(C++常用函数及测试所用)