对于后序遍历有点难度,,,
主要是在判断的时候要求访问的节点是叶子节点或者是左右节点都已经访问过了,
还有一个值得注意的点就是此处用了指针的指针,,,在栈中每一个都存储是一个地址 so我要定义一个可以存储地址的数组
#include <cstdio>
#include <cstdlib>
//define _OJ_
#define maxsize 100
typedef struct tree1
{
char data;
struct tree1 *lchild;
struct tree1 *rchild;
} tree1, *tree;
typedef struct stack1
{
tree *base;
tree *top;
} stack1, *stack;
stack
creat_stack(void)
{
stack s;
s = (stack) malloc (sizeof(stack1));
s->base = (tree*) malloc (maxsize * sizeof(tree));
s->top = s->base;
return s;
}
tree
creat_tree(tree T)
{
char ch;
scanf("%c", &ch);
if(ch == ‘#‘)
T = NULL;
else
{
T = (tree) malloc (sizeof(tree1));
T->data = ch;
T->lchild = creat_tree(T->lchild);
T->rchild = creat_tree(T->rchild);
}
return T;
}
void
push(stack s, tree T)
{
*s->top++ = T;
}
tree
pop(stack s)
{
return *--s->top;
}
tree
gettop(stack s)
{
return *(s->top - 1);
}
int
isempty(stack s)
{
if(s->top == s->base)
return 1;
else
return 0;
}
//後序遍歷
void
traverse1(tree T)
{
stack s;
s = creat_stack();
tree T1, pre;//當前節點 和 前一個訪問的節點
T1 = T; pre = NULL;
while (T1 != NULL || isempty(s) != 1) {
while (T1) {//向左走到底
push(s,T1);
T1 = T1->lchild;
}
T1 = gettop(s);
if(T1->rchild == NULL || T1->rchild == pre)
//如果无右子树或者前一个访问的就是右子树就访问此树
{
printf("%c ", T1->data);
pre = T1;
T1 = NULL;
pop(s);
}
else
T1 = T1->rchild;
}
}
void
traverse(tree T)
{
stack s;
s = creat_stack();
while (T || !isempty(s)) {
while(T)
{
push(s,T); //printf("%c\n", T->data);此處是前序遍歷
T = T->lchild;
}
if(!isempty(s))
{
T = pop(s);
printf("%c ", T->data);//此處是中序遍歷
T = T->rchild;
}
}
}
int main(int argc, char const *argv[]) {
#ifndef _OJ_ //ONLINE_JUDGE
freopen("input.txt", "r", stdin);
#endif
tree T;
T = creat_tree(T);
traverse(T);printf("\n");
traverse1(T);
return 0;
}
// ABCD BDAC DBCA