二叉树的基本操作

2023-06-26 0 1,068

二叉树的结构体定义

typedef struct BNode{
	int data;
	struct BNode *lchild,*rchild;
}BNode,BiTree;

二叉树的操作代码

//建立二叉树
BiTree createBiTree(){
	int data;
	scanf("%d",&data);
	if(data!=-1){
		t = (BNode*)malloc(sizeof(BNode));
		t->data = data;
		t->lchild = createBiTree();
		t->rchild = createBiTree();
		return t;
	}else{
		return NULL;
	}
} 

////三大递归遍历
//打印函数
void visit(BiTree T){
    printf("%d",T->data);
} 
//前序遍历
void NLRPrint(BiTree t){
	if(t){
	visit(t);
	NLRPrint(t->lchild);
	NLRPrint(t->rchild);
   }
}
//中序遍历
void LNRPrint(BiTree t){
	if(t){
	LNRPrint(t->lchild);
	visit(t);
	LNRPrint(t->rchild);
   }
}
//后续遍历
void LRNPrint(BiTree t){
	if(t){
	visit(t);
	LRNPrint(t->lchild);
	LRNPrint(t->rchild);
   }
}

////三大非递归遍历
//前序遍历
void NLRPrintN(BiTree t){
	BiTree stack[MAXSIZE],p = t;
	int top=-1;
	//stack[++top] = t;
	while(p || top!=-1){
		if(p){
			visit(p);
			stack[++top] = p;
			p = p->lchild;
		}else{
			p = stack[top--];
			p = p->rchild;
		}
	}
} 

//中序遍历
void LNRPrintN(BiTree t){
	BiTree stack[MAXSIZE],p = t;
	int top=-1;
	while(p || top!=-1){
		if(p){
			stack[++top] = p;
			p = p->lchild;
		}else{
			p = stack[top--];
			visit(p);
			p = p->rchild;
		}
	}
}

//后序遍历
void LRNPrintN(BiTree t){
	BiTree stack[MAXSIZE],p = t;
	int top = -1,tag[MAXSIZE] = {0};
	while(p || top!=-1){
		if(t){
			stack[++top] = p;
			p = p->lchild;
			tag[top] = 1;
		}else{
			if(tag[top]==1){
				tag[top] == 2;
				p = stack[top];
				p = p->rchild;
			}else{
				visit(p);
				top--;
				p = NULL;
			}
		}
	}
}

//层序遍历
void levelPrint(BiTree t){
	BiTree Queue[MAXSIZE],p=t;
	int rear = front = -1;
	Queue[++rear] = p;
	while(rear!=front){
		p = Queue[++front];
		visit(p);
		if(p->lchild){
			Queue[++rear] = p->lchild;
		}
		if(p->rchild){
			Queue[++rear] = p->rchild;
		}
	}
} 
收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

本站部分资源收集自互联网,我站仅分享内容,仅供用户个人研究,不提供商业使用,如有侵权下架处理,觉得资源内容不错请您在官方渠道购买正版,您在阅读的同时下载的内容本站不承担任何法律责任!Some resources of this website are collected from the Internet. We only share the content, which is only for personal research of users, and not for commercial use. If there is infringement and off shelf processing, please purchase the authentic version of the resource content from the official channel if you think it is good. We will not bear any legal responsibility for the content you download while reading!

橙凰素材-精品源码下载|正版主题更新 学习交流 二叉树的基本操作 https://b.bqzmz.com/2023/06/26/%e4%ba%8c%e5%8f%89%e6%a0%91%e7%9a%84%e5%9f%ba%e6%9c%ac%e6%93%8d%e4%bd%9c/

为用户提供极致的体验

上一篇: 队列题目
常见问题
  • 正版主题是指站长在指定渠道购买的官方主题,提供作者联系,资源支持,长期更新等等内容
查看详情
  • 非常抱歉,请联系网站页脚的客服,我们将在核实后下架处理并返还给您此资源的收益(会扣去网站运营的费用),谢谢理解!
查看详情
  • 网络资源是站长从互联网分享收集而来的内容,本站不会做测试,直接分享,不包源码可用性,运营性,如有需求点击右边的联系正版,谢谢!
查看详情
  • 如果资源不是最新版本,请在资源下方评论区进行催更或提交工单处理,我们会尽快更新并通过邮箱通知您。
查看详情

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务