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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值