二叉树的非递归遍历(前序、中序、后序)

定义树:

class BSTree
{
public:
    BSTree(int idata)
    {
        data = idata;
        lChild = rChild = NULL;
    }
    ~BSTree(){}
    int data;
    BSTree *lChild,*rChild;
};

///BTNode用于非递归后序遍历用
class BTNode
{
public:
    BTNode(){}
    ~BTNode(){}
    bool isFirst;
    BSTree *node;
};
///非递归前序遍历
void preOrder(BSTree *root)
{
    stack<BSTree*> s;
    BSTree *p=root;
    while(p!=NULL || !s.empty())
    {
        while(p!=NULL)
        {
            printf(" %d",p->data);
            s.push(s);
            p = p->lChild;
        }
        if(!s.empty())
        {
            p = s.top();
            s.pop();
            p = p->rChild;
        }
    }
}

///非递归中序遍历
void midOrder(BSTree* root)
{
    stack<BSTree*> s;
    BSTree *p = root;
    while(p!=NULL || !s.empty())
    {
        while(p!=NULL)
        {
            s.push(p);
            p = p->lChild;
        }
        if(!s.empty())
        {
            p = s.top();
            printf(" %d",p->data);
            s.pop();
            p = p->rChild;
        }
    }
}

///非递归后序遍历
void postOrder(BSTree *root)
{
    stack<BTNode*> s;
    BSTree *p = root;
    BTNode *temp;
    while(p!=NULL || !s.empty())
    {
        while(p!=NULL)
        {
            BTNode *bt = (BTNode *)malloc(sizeof(BTNode));
            bt->isFirst = true;
            bt->node = p;
            p = p->lChild;
        }
        if(!s.empty())
        {
            temp = s.top();
            s.pop();
            if(temp->isFirst == true)
            {
                temp->isFirst = false;
                s.push(temp);
                p = temp->node->rchild;
            }
            else
            {
                printf(" %d",temp->node->data);
                p = NULL;
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/sinat_21107433/article/details/81395318
今日推荐