二叉树的三种非递归遍历方式

#include <iostream>
#include <algorithm>
#include <stack>
#include <cmath>
#include <climits>

using namespace std;

struct Node {
    Node *left;
    Node *right;
    int value;
    Node(int v) : value(v), left(NULL), right(NULL) {}
};

// 非递归遍历二叉树
void PreOrderUnRecursive(Node *root) {
    cout << __func__ << endl;
    stack<Node *> node_stk;
    Node *p_cur = root;
    while (node_stk.size() || p_cur) {
        if (p_cur) {
            cout << p_cur->value << endl;
            if (p_cur->right)
                node_stk.push(p_cur->right);
            p_cur = p_cur->left;
        } else {
            p_cur = node_stk.top();
            node_stk.pop();
        }
    }
}

void InOrderUnRecursive(Node *root) {
    cout << __func__ << endl;
    stack<Node *> node_stk;
    Node *p_cur = root;
    while (node_stk.size() || p_cur) {
        if (p_cur) {
            node_stk.push(p_cur);
            p_cur = p_cur->left;
        } else {
            p_cur = node_stk.top();
            node_stk.pop();

            cout << p_cur->value << endl;

            p_cur = p_cur->right;
        }
    }
}

void PostOrderUnRecursive(Node *root) {
    cout << __func__ << endl;
    stack<Node *> node_stk;
    Node *p_cur = root;
    Node *p_prev = NULL;
    while (node_stk.size() || p_cur) {
        if (p_cur) {
            node_stk.push(p_cur);
            p_cur = p_cur->left;
        } else {
            Node *p_top = node_stk.top();
            if (p_top->right && p_prev != p_top->right) { // 此时左子树一定已经处理完,只需判断是否需要处理右子树
                p_cur = p_top->right;
            } else {
                node_stk.pop();
                cout << p_top->value << endl;
                p_prev = p_top;
            }
        }
    }
}

int main(int argc, char const *argv[])
{
    Node n1(1);
    Node n2(2); Node n3(3);
    Node n4(4); Node n5(5); Node n6(6); Node n7(7);
    n1.left = &n2; n1.right = &n3;
    n2.left = &n4; n2.right = &n5;
    n3.left = &n6; n3.right = &n7;

    PreOrderUnRecursive(&n1);
    InOrderUnRecursive(&n1);
    PostOrderUnRecursive(&n1);

    return 0;
}

阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页