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;
        }

  • 相关阅读:
    Mybatis JPA 插件简介(v2.1.0)
    linux-非root用户运行tomcat
    java版Web Socket,实现消息推送
    开源巨献:Google最热门60款开源项目
    java加密算法AES与RSA
    Jquery table元素操作-创建|数据填充|重置|隐藏行
    Mybatis JPA-集成方案+源码
    Mybatis JPA 插件简介
    eclipse maven构建
    初探JSP运行机制和与Servlet间的关系
  • 原文地址:https://www.cnblogs.com/qingjiaowoxiaoxioashou/p/5964630.html
Copyright © 2011-2022 走看看