void PostOrder(BiTree T) { SqStack S; InitStack(&S); BiTNode *p = T; BiTNode *r = NULL; while (p || !IsEmpty(&S)) { if (p) // 走到最左边 { push(&S, *p); p = p->lchild; } else // 向右 { GetTop(S, *p); // 读栈顶结点(非出栈) if (p->rchild && p->rchild != r) // 若右子树存在,且未被访问过 p = p->rchild; // 转向右 else // 否则,弹出结点并访问 { pop(&S, p); // 将节点弹出 printf("%c ", p->data); // 访问该节点 r = p; // 记录最近访问过的结点 p = NULL; // 结点访问完后,重置p指针 } } } }
时间: 2024-02-10 18:07:26 浏览: 67
BiTree二叉树
好的,根据您提供的程序,以下是一个完整的C语言程序:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef char ElemType;
typedef struct BiTNode {
ElemType data;
struct BiTNode *lchild, *rchild;
} BiTNode, *BiTree;
typedef struct {
BiTNode data[MAXSIZE];
int top;
} SqStack;
void InitStack(SqStack *S) {
S->top = -1;
}
int IsEmpty(SqStack *S) {
if (S->top == -1) {
return 1;
} else {
return 0;
}
}
int push(SqStack *S, BiTNode e) {
if (S->top == MAXSIZE - 1) {
return 0;
}
S->top++;
S->data[S->top] = e;
return 1;
}
int pop(SqStack *S, BiTNode *e) {
if (S->top == -1) {
return 0;
}
*e = S->data[S->top];
S->top--;
return 1;
}
int GetTop(SqStack S, BiTNode *e) {
if (S.top == -1) {
return 0;
}
*e = S.data[S.top];
return 1;
}
void PostOrder(BiTree T) {
SqStack S;
InitStack(&S);
BiTNode *p = T;
BiTNode *r = NULL;
while (p || !IsEmpty(&S)) {
if (p) {
push(&S, *p);
p = p->lchild;
} else {
GetTop(S, p);
if (p->rchild && p->rchild != r) {
p = p->rchild;
} else {
pop(&S, p);
printf("%c ", p->data);
r = p;
p = NULL;
}
}
}
}
int main() {
// 构造一棵二叉树
BiTNode node1 = {'A', NULL, NULL};
BiTNode node2 = {'B', NULL, NULL};
BiTNode node3 = {'C', NULL, NULL};
BiTNode node4 = {'D', NULL, NULL};
BiTNode node5 = {'E', NULL, NULL};
BiTNode node6 = {'F', NULL, NULL};
BiTNode node7 = {'G', NULL, NULL};
BiTNode node8 = {'H', NULL, NULL};
BiTNode node9 = {'I', NULL, NULL};
node1.lchild = &node2;
node1.rchild = &node3;
node2.lchild = &node4;
node2.rchild = &node5;
node3.lchild = &node6;
node3.rchild = &node7;
node5.rchild = &node8;
node7.lchild = &node9;
BiTree T = &node1;
PostOrder(T); // 输出二叉树的后序遍历结果
return 0;
}
```
注意,这里只是一个示例程序,您需要根据具体需求进行修改和调整。
阅读全文