码迷,mamicode.com
首页 > 其他好文 > 详细

前序、中序、后序遍历二叉树的非递归实现

时间:2015-02-24 16:16:46      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:

class Node
{
public:
    int data;
    Node* left;
    Node* right;
};

void pre-order(Node* root)
{
    stack<Node*> stk;
    if (root)
        stk.push(root);
    while (!stk.empty())
    {
        Node* nd = stk.top();
        cout << nd->data << endl;
        stk.pop();
        if (nd->right)
            stk.push(nd->right);
        if (nd->left)
            stk.push(nd->left);
    }
}

void in-order(Node* root)
{
    stack<Node*> stk;
    Node* nd = root;
    while (nd)
    {
        stk.push(nd);
        nd = nd->left;
    }
    while (!stk.empty())
    {
        nd = stk.top();
        cout << nd->data << endl;
        stk.pop();
        Node* nd2 = nd->right;
        while (nd2)
        {
            stk.push(nd2);
            nd2 = nd2->left;
        }
    }
}

void post-order(Node* root)
{
    // 使用双队列
    stack<Node*> stk1, stk2;
    if (root)
        stk1.push(root);
    while (!stk1.empty())
    {
        Node* nd = stk1.top();
        stk1.pop();
        stk2.push(nd);
        if (nd->left)
            stk1.push(nd->left);
        if (nd->right)
            stk1.push(rd->right);
    }
    while (!stk2.empty())
    {
        Node* nd = stk2.top();
        cout << nd->data << endl;
        stk2.pop();
    }
}

 

前序、中序、后序遍历二叉树的非递归实现

标签:

原文地址:http://www.cnblogs.com/litao-tech/p/4298726.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!