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

  • 相关阅读:
    (原)x264代码中的码流控制学习
    (原)关于OpenSL ES播放音频数据的一个奇怪的问题
    (原)理解码率控制模式(x264,x265,vpx)
    CentOS清除用户登录记录和命令历史方法
    2B销售提升业绩的5项技能
    Cookie中的httponly的属性和作用
    如何开展HW行动
    护网结束,复盘攻防,聊聊安全! 2019
    2018-11-21(34)《阿里铁军》阅后记!
    你了解渗透测试与红蓝队对抗的区别吗?
  • 原文地址:https://www.cnblogs.com/qingjiaowoxiaoxioashou/p/5964630.html
Copyright © 2011-2022 走看看