二叉树的遍历

二叉树的抽象数据类型定义

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");

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值