建立过程:通过栈来模拟递归建立。先将根压入栈中,然后不断的加左子树,遇到空则加右子树;在开始不断的加左子树...一直 重复下去直到读取到回车。(创建时不要对传入的根直接操作,否者最后返回去的东西不对)。
遍历过程:通过两个栈来实现。s栈进行遍历过程,r栈存放结果。因为要后续输出,所以遍历是应该为根->右子树->左子树。开 始遍历,如果节点node不为空这把这个节点放入 s 与 r 中,然后node=node->rchild;如果node为空,则把s栈顶元素 弹出,node指向弹出元素的右子树...重复执行直到s栈为空。
参考链接:https://www.jianshu.com/p/fff56a761dde
#include<stdlib.h>
#include<stdio.h>
typedef char TElemType;
typedef struct BiTNode{ //树
TElemType data;
struct BiTNode *lchild, *rchild;
}BiTNode, *BiTree;
#define STACK_INIT_SIZE 100
#define STACKINCREASE 10
typedef BiTree SElemType;
typedef struct{
SElemType *base;
SElemType *top; //栈顶指针
int stacksize; //当前以分配存储空间
}SqStack;
void InitStack(SqStack &S){
S.base=NULL;
S.base=(SElemType *)malloc(STACK_INIT_SIZE*sizeof(SElemType));
if(!S.base){
printf("栈分配失败!\n");
exit(-1);
}
S.top = S.base;
S.stacksize = STACK_INIT_SIZE;
}
void Push(SqStack &S, BiTree &e){ //压栈
if(S.top - S.base >= S.stacksize){
S.base = (SElemType *)realloc(S.base,(STACKINCREASE+STACK_INIT_SIZE)*sizeof(BiTNode)); //栈满。追加空间
if(!S.base){
printf("栈分配失败!\n");
exit(-1);
S.top = S.base+S.stacksize;
S.stacksize +=STACKINCREASE;
}
}
*(S.top) = e;
S.top++;
}
BiTree GetTop(SqStack S){ //获得栈顶元素
if(S.top == S.base){
return 0;
}
return *(S.top-1);
}
BiTree Pop(SqStack &S){ //出栈
if(S.top == S.base){
return 0;
}
S.top--;
return *S.top;
}
int Empty(SqStack S){
if(S.top == S.base){ //判断栈是否为空 1为空
return 1;
}
return 0;
}
void CreatBiTree(BiTree &P){
//先序创建二叉树,空格表示空树
char tmp;
scanf("%c",&tmp);
if(tmp==' '){
P=NULL;
printf("This is a empty tree!\n");
return ;
}
P=(BiTree)malloc(sizeof(BiTNode));
BiTree T=P;
T->data=tmp;
SqStack s;
InitStack(s);
Push(s,T);
while(!Empty(s)){
while(scanf("%c",&tmp)){
T=GetTop(s);
if(tmp == ' '){
T->lchild = NULL;
break;
}
T->lchild = (BiTree)malloc(sizeof(BiTNode));
T->lchild->data = tmp;
Push(s,T->lchild);
}
while(scanf("%c",&tmp)){
if(tmp == '\n') return ;
T=GetTop(s);
if(tmp!=' '){
T->rchild = (BiTree)malloc(sizeof(BiTNode));
T->rchild->data = tmp;
BiTree a=Pop(s);
Push(s,T->rchild);
break;
}
T->rchild = NULL;
T=Pop(s);
}
}
}
void Print(TElemType e){
//打印字符
putchar(e);
}
void PostOrderTraverse(BiTree T,void (*visit)(TElemType e)){
//非递归实现后序遍历
SqStack s,r;
InitStack(s);
InitStack(r);
BiTree p=T;
while(!Empty(s) || p){
if(p){
Push(s,p);
Push(r,p);
p=p->rchild;
}else{
p = Pop(s);
p=p->lchild;
}
}
while(!Empty(r)){
p=Pop(r);
visit(p->data);
}
}
int main()
{
BiTree t;
//t=(BiTree)malloc(sizeof(BiTNode));
CreatBiTree(t);
printf("后续遍历:\n");
PostOrderTraverse(t,Print);
printf("\n\n");
return 0;
}