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

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


}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值