二叉树的非递归遍历
#include<stdio.h>
#include<stdlib.h>
#include"myStack.h" //使用数组形式的栈
//非递归遍历可以使用下列规则
/*
每个节点设置一个标志位,默认状态为假
- 将根节点压入栈中
- 进入循环:只要栈中元素个数大于0,进行循环操作
- 弹出栈顶元素
- 如果这个栈顶元素标志为真,输出这个元素并执行下一次循环
- 如果栈顶元素标志为假,将节点的标志设为真
- 将该节点的右子树、左子树、根压入到栈中
- 执行下一次循环
*/
#define FALSE 0
#define TRUE 1
struct myBinaryTree{
char ch; //数据域
struct myBinaryTree* lChild;
struct myBinaryTree* rChild;
int flag;
};
//参数:根节点
void foreachPrint(struct myBinaryTree* b){
if(NULL == b){
return;
}
myStackType* st = init_stack(); //初始化一个栈
push_stack(st, b); //根节点入栈
while(size_stack(st) > 0){ //栈中元素大于0,继续循环
//获取栈顶元素,并出栈
struct myBinaryTree* curNode = top_stack(st);
pop_stack(st);
if(curNode->flag == TRUE){ //标志位为真
printf("%c\n", curNode->ch);
continue;
}else{ //标志位为假
curNode->flag = TRUE;
if(curNode->rChild != NULL){ //子树为空就不入栈
push_stack(st, curNode->rChild);
}
if(curNode->lChild != NULL){
push_stack(st, curNode->lChild);
}
push_stack(st, curNode);
}
}
}
int main(){
struct myBinaryTree bt1 = {'A',NULL,NULL, FALSE};
struct myBinaryTree bt2 = {'B',NULL,NULL, FALSE};
struct myBinaryTree bt3 = {'C',NULL,NULL, FALSE};
struct myBinaryTree bt4 = {'D',NULL,NULL, FALSE};
struct myBinaryTree bt5 = {'E',NULL,NULL, FALSE};
struct myBinaryTree bt6 = {'F',NULL,NULL, FALSE};
struct myBinaryTree bt7 = {'G',NULL,NULL, FALSE};
struct myBinaryTree bt8 = {'H',NULL,NULL, FALSE};
bt1.lChild = &bt2;
bt1.rChild = &bt6;
bt2.rChild = &bt3;
bt3.lChild = &bt4;
bt3.rChild = &bt5;
bt6.rChild = &bt7;
bt7.lChild = &bt8;
foreachPrint(&bt1);
return 0;
}