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

  • 相关阅读:
    在使用IO流时该选择何种流对象
    对Java中的File类的一些理解
    AlarmManager实现闹钟功能
    Android 中 Movie 类显示GIF图片
    Java对象序列化和serialVersionUID [转载]
    Git常用命令行操作
    Android中常用的编码和解码(加密和解密)的问题
    Android apk反编译 和 防止反编译
    Bitmap 图片二次采样 【转载】
    Android:瀑布流效果 的简单实现
  • 原文地址:https://www.cnblogs.com/mengjuanjuan/p/10545931.html
Copyright © 2011-2022 走看看