zoukankan      html  css  js  c++  java
  • 二叉树的非递归遍历(前序,中序,后序和层序遍历)

    void _PrevOrderNR(Node* root)    //非递归前序遍历
        {
            if (root == NULL)
                return;

            Node* cur = root;
            stack<Node*> s;
            while(cur||!s.empty())
            {
                while (cur)
                {
                    cout << cur->_data << "  ";
                    s.push(cur);
                    cur = cur->_left;
                }

                Node* top = s.top();
                s.pop();
                cur = top->_right;
            }
            cout << endl;
        }

        void _InOrderNR(Node* root)    //非递归中序遍历
        {
            Node* cur = root;
            stack<Node*> s;
            while (cur || !s.empty())
            {
                while (cur)
                {
                    s.push(cur);
                    cur = cur->_left;
                }

                Node* top = s.top();
                cout << top->_data << "   ";
                s.pop();
                cur = top->_right;
            }
            cout << endl;
        }

        void _PostOrderNR(Node* root)    //非递归后序遍历
        {
            stack<Node*> s;
            Node* cur = root;
            Node* prev = NULL;
            while (cur || !s.empty())
            {
                while (cur)
                {
                    s.push(cur);
                    cur = cur->_left;
                }

                Node* top = s.top();
                if (top->_right == NULL || top->_right == prev)
                {
                    cout << top->_data << "  ";
                    prev = top;
                    s.pop();
                }
                else
                {
                    cur = top->_right;
                }
            }
            cout << endl;
        }

        void _LevelOrder(Node* root)   //层序遍历
        {
            
            Node* cur = root;
            queue<Node*> q;        
            if (root)
                q.push(root);
            while (!q.empty())
            {
                Node* front = q.front();
                q.pop();
                cout << front->_data << "  ";
                if (front->_left)
                    q.push(front->_left);
                if (front->_right)
                    q.push(front->_right);
            }
            cout << endl;
        }

  • 相关阅读:
    CentOS6.8下查看yum及rpm安装后的软件位置
    rabbitmq的web管理界面无法使用guest用户登录
    CentOS6.8搭建rabbitmq消息中间件
    Study 3 —— Python运算符
    CentOS6.x网易163yum源配置
    CentOS6.8下Jenkins+maven+tomcat+git+shell自动构建、部署web应用环境的搭建
    CentOS6.8下安装memcached并设置开机自启动
    CentOS6.8下安装redis并配置开机自启动
    CentOS下查找java环境变量
    CentOS下设置vim的tab键为4格
  • 原文地址:https://www.cnblogs.com/qingjiaowoxiaoxioashou/p/5964630.html
Copyright © 2011-2022 走看看