二叉树的抽象数据类型定义
typedef char data_t;
typedef struct node_st{
data_t data;
struct node_st *l,*r;
}bitree;
//创建二叉树
bitree* create(){
bitree* t;
data_t ch;
scanf("%c",&ch);
if(ch=='#'){
return NULL;
}
if((t = malloc(sizeof(*t))) == NULL){
printf("malloc failed!\n");
return NULL;
}
t->data = ch;
t->l = create();
t->r = create();
return t; //返回树根
}
先序遍历
递归算法:
void preorder(bitree* t){
if(t==NULL){
return ;
}
printf("%c ",t->data);
preorder(t->l);
preorder(t->r);
}
非递归算法:
void PreOrder(bitree T) {
SqStack S;
InitStack(S);
bitree p;
p = T;
while (p || !IsEmpty(S)) {
if (p) {
printf("%d ",p->data);//访问该结点
st_push(S, p);
p = p->l;
}
else {
st_pop(S, p);//栈顶元素出栈
p = p->r;
}
}
中序遍历
递归算法:
void inorder(bitree* t){
if(t==NULL){
return ;
}
inorder(t->l);
printf("%c ",t->data);
inorder(t->r);
}
非递归算法:
void InOrder(bitree T) {
SqStack S;
InitStack(S);
bitree p; //当前结点
p = T;
while (p || !IsEmpty(S)) {
if (p) {
st_push(S, p);
p = p->l;
}
else {
st_pop(S, p);
printf("%d ",p->data);
p = p->r;//判断右孩子
}
}
}
后序遍历
递归算法:
void postorder(bitree* t){
if(t==NULL){
return ;
}
postorder(t->l);
postorder(t->r);
printf("%c ",t->data);
}
非递归算法:
void Postorder(bitree T) {
bitree p;
Sqstack S;
if (T == NULL) {
return;
}
InitStack(S); // 初始化栈
p = T;
while (1) {
if (p != NULL) { // p 非空,则入栈,之后 p 向左走
push(S, p);
p = p->l;
} else { // p 为空,则出栈
if (!StackEmpty(S)) { // 确保栈不为空
pop(S, p);
if (p->r == NULL || p->flag == 1) { // 右为空或已访问过左右子树
printf("%d ", p->data);
p = NULL; // 访问后置空
} else { // 右非空,则 p 重新入栈,重复入栈标志 flag 置为真,之后 p 向右走
push(S, p);
p->flag = 1;
p = p->r;
}
} else { // 栈为空,退出循环
break;
}
}
}
}
层序遍历
void levelorder(bitree* t){
linkqueue* qu;
if((qu=queue_create())==NULL){
return ;
}
if(t==NULL){
return ;
}
printf("%c ",t->data); //取出根节点的值
enqueue(qu,t); //入队保存根节点
while(!queue_empty(qu)){
dequeue(qu,&t); //出队
if(t->l){
printf("%c ",t->l->data);
enqueue(qu,t->l);
}
if(t->r){
printf("%c ",t->r->data);
enqueue(qu,t->r);
}
}
printf("\n");
}