一个函数实现树的非递归前、中、后序遍历
程序员文章站
2022-06-12 10:14:50
...
#include<iostream>
#define MAX 99
using namespace std;
struct BTNode {
int data;
BTNode *lchild, *rchild;
};
void visit(BTNode *p) {//访问
printf("%d ", p->data);
}
void Pre_IN_Post_order(BTNode *p,int AA) {//AA=1先序 2中序 3后序
BTNode* sta[MAX];//定义一个栈
int top = -1;//栈顶指针
int flag[MAX] = {};//记录第几次访问,初始化都是0
sta[++top] = p;
while (top!=-1) {
p = sta[top];
++flag[top];
if (flag[top] == AA) visit(p);
switch (flag[top]) {
case 1:
if (p->lchild) sta[++top] = p->lchild; break;
case 2:
if (p->rchild) sta[++top] = p->rchild; break;
case 3:
flag[top--]=0;break;//为下一个可能入栈的元素进行初始化
}
}
}
int main() {
int a[5] = { 1,2,3,4,5 };
BTNode all[9];
for (int i = 0; i < 9; ++i) {
all[i].lchild = all[i].rchild = NULL;
all[i].data = i;
}
all[0].lchild = all + 1; all[0].rchild = all + 2;
all[1].lchild = all + 3; all[1].rchild = all + 4;
all[2].lchild = all + 5; all[2].rchild = all + 6;
all[4].lchild = all + 7;
all[5].rchild = all + 8;
Pre_IN_Post_order(all, 1); cout << endl;
Pre_IN_Post_order(all, 2); cout << endl;
Pre_IN_Post_order(all, 3); cout << endl;
}