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

    #include <iostream>
    #include <stack>
    #include <vector>
    #include <string>
    using namespace std;

    class BTNode
    {
    public:
    int val;
    BTNode* left;
    BTNode* right;
    BTNode(int x): val(x), left(NULL), right(NULL)
    {}
    };
    //二叉树的非递归遍历
    //前序遍历
    void PreNonRecur(BTNode* root)
    {
    if (!root)
    {
    return ;
    }
    BTNode* p = root;
    stack<BTNode*> s;
    while (!s.empty() || p)
    {
    //p不空,遍历左子树,进栈
    while (p)
    {
    cout << p->val << " ";
    s.push(p);
    p = p->left;
    }

    //p为空,出栈
    if (!s.empty())
    {
    p = s.top();
    s.pop();
    p = p->right;

    }
    }
    cout << endl;
    }
    //中序遍历
    void MidNonRecur(BTNode* root)
    {
    if (!root)
    {
    return ;
    }
    BTNode* p = root;
    stack<BTNode*> s;
    while (!s.empty() || p)
    {
    //p不空,遍历左子树,进栈
    while (p)
    {
    s.push(p);
    p = p->left;
    }

    //p为空,出栈
    if (!s.empty())
    {
    p = s.top();
    s.pop();
    cout << p->val << " ";
    p = p->right;

    }
    }
    cout << endl;
    }
    //后序遍历
    void LastNonRecur(BTNode* root)
    {
    if (!root)
    {
    return;
    }
    BTNode* pCur = root;
    BTNode* pLastVisit = NULL;
    stack<BTNode*> s;
    while (pCur)
    {
    s.push(pCur);
    pCur = pCur->left;
    }
    while (!s.empty())
    {
    pCur = s.top();
    s.pop();
    if (!pCur->right || pCur->right == pLastVisit)
    {
    cout << pCur->val << " ";
    pLastVisit = pCur;
    }
    else
    {
    s.push(pCur);
    pCur = pCur->right;
    while (pCur)
    {
    s.push(pCur);
    pCur = pCur->left;
    }
    }
    }
    cout << endl;
    }

    int main()
    {
    BTNode a(1);
    BTNode b(2);
    BTNode c(3);
    BTNode d(4);
    BTNode e(5);
    BTNode f(6);
    a.left = &b;
    a.right = &c;
    b.left = &d;
    b.right = &e;
    e.right = &f;
    PreNonRecur(&a);
    system("pause");
    return 0;
    }

  • 相关阅读:
    解决eclipsehelios中Errors running builder JavaScript Validator的问题
    oracle sequence cache
    离开页面前调用Js方法
    精典的148句话
    DB2 应用
    现有portal项目(商业的和开源的)解决方案及优缺点
    管理铁律
    myeclipse 6.0 弹出 Multiple Errors have Occurred 错误
    绝对经典的表记录操作(超越版)
    DB2中不同于其它数据库的操作
  • 原文地址:https://www.cnblogs.com/mengjuanjuan/p/10545931.html
Copyright © 2011-2022 走看看