代码改变世界

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

2015-02-24 15:32  李涛的技术博客  阅读(148)  评论(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();
    }
}