C++非递归的前中后序遍历实现

来源:互联网 发布:js null的valueof 编辑:程序博客网 时间:2024/06/01 07:48

current 指针是root指针,即开始遍历的点
被注释掉的部分是递归的实现,在这三种遍历中,前序和中序遍历的套路相同,在后序遍历是,新增了一个struct来保存每个点被弹出过的次数是否到达了3次,以此来决定是否可以输出,

template <class Type> void BinaryTree<Type>::preOrder(    BinTreeNode <Type> *current){    /*if (current != NULL) {        cout << current->data << ' ';        preOrder(current->leftChild);        preOrder(current->rightChild);    }*/    BinTreeNode<Type> * p;    p = current;    stack<BinTreeNode<Type>*> s;    do {        while (p) {            cout << p->data << ' ';            s.push(p);            p = p->leftChild;        }        if (!s.empty()) {            p = s.top();            s.pop();            p = p->rightChild;        }    } while (p || !s.empty());}template <class Type> void BinaryTree<Type>::inOrder(BinTreeNode <Type> *current) {/*( if (current != NULL) {        inOrder(current->leftChild);        cout << current->data << ' ';        inOrder(current->rightChild);    }*/    BinTreeNode<Type> *p;    p = current;    stack<BinTreeNode<Type>*> s;    do {        while (p) {            s.push(p);            p = p->leftChild;        }        if (!s.empty()) {            p = s.top();            s.pop();            cout << p->data << ' ';            p = p->rightChild;        }    } while (p || !s.empty());}template <class Type> struct StNode {    //后序遍历使用的递归工作栈  结点定义            const BinTreeNode <Type> *Node;  //结点指针    int TimesPopped;                      //退栈次数    StNode(const BinTreeNode <Type> *n =        NULL) : Node(n), TimesPopped(0) { }};template <class Type> void BinaryTree<Type>::postOrder(BinTreeNode <Type> *current) {    /*if (current != NULL) {        postOrder(current->leftChild);        postOrder(current->rightChild);        cout << current->data << ' ';    }*/    stack<StNode<Type>> s;    StNode<Type> p;    s.push(StNode<Type>(current));    while (!s.empty()) {        p = s.top();        s.pop();        while(++p.TimesPopped == 3) {            cout << p.Node->data << ' ';             if (!s.empty()) {                p = s.top();                s.pop();            }        }             s.push(p);            if (p.TimesPopped == 1) {                if (p.Node->leftChild != NULL) {                    s.push(StNode<Type>(p.Node->leftChild));                }            }          else if(p.TimesPopped == 2) {                    if (p.Node->rightChild != NULL) {                        s.push(StNode<Type>(p.Node->rightChild));                    }                }          else {              break;          }        } }
阅读全文
0 0