树的递归和非递归遍历

ε祈祈猫儿з 提交于 2019-11-29 23:41:38
利用循环和栈实现前序、中序和后序遍历、利用队列实现层次遍历
typedef struct node  
{  
    int data;
    int cnt;//在后序遍历中使用,子树的根节点在第一次遍历的时候不会输出,只有在第二次遍历的时候才输出。
    struct node *lchild;  
    struct node *rchild;
}bitree;
stack<node*> s;

前序遍历
//针对一个根结点,先输出其根结点值,再push其所有左结点,然后再弹出一个结点取其右结点作为新的根结点。
void preorder(bitree *t)//前序遍历的非递归算法
{
     
    bitree *temp = t;
    while(temp != NULL || !s.empty())
    {
        //遍历所有左结点
        while(temp != NULL)//先遍历左孩子,并输出。
        {
            printf("%4d",temp->data);
            s.push(temp);
            temp = temp->lchild;
        }
        if(!s.empty())//当左孩子遍历完后,取栈顶,找右孩子。此时循环还没有结束,再遍历它的左孩子,直至孩子全部遍历结束。
        {
            temp = s.top();
            s.pop();
            temp = temp->rchild;
        }
    }
    printf("\n");
}

中序遍历
void inorder(bitree *t)//中序遍历的非递归算法
{
    bitree *temp = t;
    while(temp != NULL || !s.empty())
    {
        while(temp != NULL)//先把左孩子入栈,所有左孩子入栈结束
        {
            s.push(temp);
            temp = temp->lchild;
        }
        if(!s.empty())//左孩子入栈结束,取栈顶,输出栈顶元素,遍历右孩子
        {
            temp = s.top();
            s.pop();
            printf("%4d",temp->data);
            temp = temp->rchild;
        }
    }
    printf("\n");
}

后序遍历
void postorder(bitree *root)
{
    bitree *pre = NULL;
    s.push(root);
    while (!s.empty())
    {
        bitree * temp = s.top();
        if ((temp->left == NULL && temp->right == NULL) //当前结点不存在孩子结点,则可直接访问
            || (pre != NULL && pre == temp->left || pre == temp->right))//当前结点的孩子结点已被访问
        {
            printf("%4d",temp->data);
            s.pop();
            pre = temp; 
        } 
        else
        {
            if (temp->right)//入栈先入右孩子再入左孩子,保证左孩子先于右孩子访问
                s.push(temp->right);
            if(temp->left)
                s.push(temp->left);  
        }
     }
    printf("\n");
}
层次遍历
void levelorder(bitree *root)//层次遍历的非递归算法
{
    queue<bitree*> q;
    q.push(root);
    
    while (!q.empty())
    {
        bitree * tmp = q.front();
        q.pop();
        if(tmp)
        {
            printf("%4d",tmp->data);
            if (tmp->lchild)
                q.push(tmp->lchild);
            if (tmp->rchild)
                q.push(tmp->rchild);
        }
    }
    printf("\n");
        
}




 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!