#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;
}
C语言二叉树的非递归遍历
最新推荐文章于 2023-12-31 18:30:06 发布