C语言二叉树的非递归遍历

#include <iostream>
#include <stack>
using namespace std;

/*
	1、将根节点 压入栈中
	2、只要 栈size> 0  执行循环
		2.1 拿出栈顶元素
		2.2 如果栈顶元素的标志位 真    直接输出  执行下一次循环
		2.3 如果不是真 该flag的标志位真
		2.4 将  右子节点  和 左子节点  和 根 入栈
		2.5 执行下一次循环
*/

typedef struct BinaryTree {
    int value;
    struct BinaryTree* Left;
    struct BinaryTree* Right;
    bool flag;  
}BinaryTrees;

void pre_trial(BinaryTrees *p_node) {
    stack<BinaryTrees *> stack_help;
    stack_help.push(p_node);
    while(stack_help.size() > 0){
        BinaryTrees *node_help = stack_help.top();
        stack_help.pop();
        if(node_help -> flag) {
            cout << node_help -> value << " ";
            continue;
        } else {
            node_help -> flag = true;
            //前序遍历
            if(node_help -> Right != NULL)
                stack_help.push(node_help -> Right);
            if(node_help -> Left != NULL)
                stack_help.push(node_help -> Left);
            stack_help.push(node_help);

            //中序遍历
            //if(node_help -> Right != NULL)
                //stack_help.push(node_help -> Right);
            //stack_help.push(node_help);
            //if(node_help -> Left != NULL)
                //stack_help.push(node_help -> Left);

            //后序遍历
            //stack_help.push(node_help);
            //if(node_help -> Right != NULL)
                //stack_help.push(node_help -> Right);
            //if(node_help -> Left != NULL)
                //stack_help.push(node_help -> Left);
        }
    }
}

int main() {
    BinaryTrees n1 = {1, NULL, NULL, false};
    BinaryTrees n2 = {2, NULL, NULL, false};
    BinaryTrees n3 = {3, NULL, NULL, false};
    BinaryTrees n4 = {4, NULL, NULL, false};
    BinaryTrees n5 = {5, NULL, NULL, false};
    BinaryTrees n6 = {6, NULL, NULL, false};
    BinaryTrees n7 = {7, NULL, NULL, false};
    BinaryTrees n8 = {8, NULL, NULL, false};
    n1.Left = &n2;
    n1.Right = &n3;
    n2.Left = &n4;
    n2.Right = &n5;
    n3.Left = &n6;
    n3.Right = &n7;
    n4.Left = &n8;
    pre_trial(&n1);
    system("pause");
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值