zoukankan      html  css  js  c++  java
  • 树的非递归遍历

    前序非递归遍历

    void preOrder2(BinTree *root)     //非递归前序遍历 
    {
        stack<BinTree*> s;
        BinTree *p=root;
        while(p!=NULL||!s.empty())
        {
            while(p!=NULL)
            {
                cout<<p->data<<" ";
                s.push(p);
                p=p->lchild;
            }
            if(!s.empty())
            {
                p=s.top();
                s.pop();
                p=p->rchild;
            }
        }
    }

    中序非递归遍历

    void inOrder2(BinTree *root)      //非递归中序遍历
    {
        stack<BinTree*> s;
        BinTree *p=root;
        while(p!=NULL||!s.empty())
        {
            while(p!=NULL)
            {
                s.push(p);
                p=p->lchild;
            }
            if(!s.empty())
            {
                p=s.top();
                cout<<p->data<<" ";
                s.pop();
                p=p->rchild;
            }
        }    
    }

    后序非递归遍历

    要保证根结点在左孩子和右孩子访问之后才能访问,因此对于任一结点P,先将其入栈。如果P不存在左孩子和右孩子,则可以直接访问它;或者P存 在左孩子或者右孩子,但是其左孩子和右孩子都已被访问过了,则同样可以直接访问该结点。若非上述两种情况,则将P的右孩子和左孩子依次入栈,这样就保证了 每次取栈顶元素的时候,左孩子在右孩子前面被访问,左孩子和右孩子都在根结点前面被访问。

    void postOrder3(BinTree *root)     //非递归后序遍历
    {
        stack<BinTree*> s;
        BinTree *cur;                      //当前结点 
        BinTree *pre=NULL;                 //前一次访问的结点 
        s.push(root);
        while(!s.empty())
        {
            cur=s.top();
            if((cur->lchild==NULL&&cur->rchild==NULL)||
               (pre!=NULL&&(pre==cur->lchild||pre==cur->rchild)))
            {
                cout<<cur->data<<" ";  //如果当前结点没有孩子结点或者孩子节点都已被访问过 
                  s.pop();
                pre=cur; 
            }
            else
            {
                if(cur->rchild!=NULL)
                    s.push(cur->rchild);
                if(cur->lchild!=NULL)    
                    s.push(cur->lchild);
            }
        }    
    }
  • 相关阅读:
    VS Code中Vetur与prettier、ESLint联合使用
    export 和 export default 的区别,exports 与 module.exports的区别
    css clearfix实现
    通过表单自动提交,实现页面转发
    .net webapi后台返回pdf文件流,前端ajax请求下载,空白pdf排错经历
    MS Sql Service 记一次in查询的优化
    MS SQL Service 查看执行计划
    ContOS7挂载硬盘
    centos命令行连接redis服务器
    如何造轮子
  • 原文地址:https://www.cnblogs.com/hotsnow/p/10078305.html
Copyright © 2011-2022 走看看