开发者社区> 问答> 正文

树的应用 要求:实现树的前序、后序遍历的递归、非递归算法,层次遍历的非递归算法,用C++实现

求告诉啊,大神们

展开
收起
知与谁同 2018-07-22 15:59:24 2176 0
1 条回答
写回答
取消 提交回答
  • 社区管理员
    void DLR(BinaryTree *p) //前序遍历递归算法
    {
        if(p!=NULL)
        {
            cout<<p->data<<endl;
            DLR(p->lchild);
            DLR(p->rchild);
        }
    } void DLR(BinaryTree *p) //前序遍历非递归算法
    {
        stack<BinaryTree> *s;    //定义堆栈s
        BinaryTree *p=root;    //指向根节点
        while(p!=NULL || !s.empty())    
        {
            while(p!=NULL)
            {
                cout<<p->data<<endl;
                s.push(p);
                p=p->lchild;
            }
            if(!s.empty())
            {
                p=s.top();
                s.pop();
                p=p->rchild;
            }
        }
    } void LRD(BinaryTree *p) //后序遍历递归算法
    {
        if(p!=NULL)
        {
            LRD(p->lchild);
            LRD(p->rchild);
            cout<<p->data<<endl;
        }
    } void LRD(BinaryTree *p)  //后序遍历非递归算法
    {
        stack<BinaryTree> *s;    //定义堆栈s
        BinaryTree *current=p;    //当前节点
        BinaryTree *pre=NULL;    //前一节点
        while(current!=NULL || !S.empty())
        {
            while(current!=NULL)
            {
                s.push(current);
                current=current->lchild;
             }
             current=s.top();
             if(current->rchild==NULL || current->rchild==pre)
             {
                 cout<<current->data<<endl;
                 pre=current;
                 s.pop();
                 current=NULL;
             }
             else current=current->rchild;
         }
    } void levelTrace(BinaryTree *p) //层次遍历
    {
        queue<BinaryTree> *q;    //定义队列q
        BinaryTree *t=p;    
        if(visit(t))  q.push(t)    //visit()代表已被遍历过
        while(!q.empty())
        {
            t=q.front();
            q.pop();
            if(visit(t->lchild))
                q.push(t->lchild);
            if(visit(t->rchild))
                q.push(t->rchild);
        }
    }
    2019-07-17 22:55:08
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
数据+算法定义新世界 立即下载
袋鼠云基于实时计算的反黄牛算法 立即下载
Alink:基于Apache Flink的算法平台 立即下载