首页 > 编程知识 正文

用凹入表打印二叉树,二叉树按层输出

时间:2023-05-06 10:39:20 阅读:14386 作者:658

二叉树层序遍历和纵向打印说明代码部分测试用例

说明

这里二叉树的输入法保持根的左右两侧,空子树用“^”代替,不熟悉的朋友可以简单预览:二叉树表达方式

二叉树的层序遍历在这里是利用队列实现的,但二叉树的纵向打印实际上就像反向遍历一样,这部分内容并不太难,仅供参考。

代码段# define _ CRT _ secure _ no _ warnings # include stdio.h # include stdlib.h # include string.h # include windode #define Status int//二叉树//非递归二叉树//层序遍历----队列中的类型结构节点{ char data; 结构节点*液晶屏; 结构节点*字符; }BiTNode,* BiTree; 类型描述树队列元素类型; //重点//在此为循环队列typedefstructqu { queuelementtypeele [ maxsize ]; int front; int rear; (}队列; 语音识别(bi tree * Bt ); 语音目录(bi tree * Bt ); 语音识别(bi tree * Bt ); 语音(队列* q ); Statusenterq(queue*q,QueueElementType x ); statusdeleteq(queue*q,QueueElementType* x ); 状态isempty (queue * q ); voiddestroyq (队列* q ); Statuslayorder(bitreeBt; 语音识别(bi tree * Bt ) {char ch; scanf_s('%c ',ch,1 ); if(ch=='^ ' ) { * Bt=空; }else{*Bt=(bitnode* ) malloc (sizeof ) bitnode ); if(Bt ) ) Bt )-data=ch; createbitree (() Bt )-LChild ); //左边的子树createbitree () () Bt(-rchild ) ); //生成右子树} }返回; (//删除二叉树-------一般是删除后手) /因此在后手的遍历中丢弃二叉树,按照左子代、右子代、根节点的顺序丢弃。 //注意:根节点将根节点指向空,不要成为野指针。 语音目录(bi tree * Bt ) free ) Bt; 返回; }voiddestroybitree(bitree*Bt ) if ) (Bt )==NULL ) {printf ) )此二叉树为空,无法进行删除操作! n '; 返回; (else ) destroybitree (() Bt(-lchild ) ); destroybitree (() Bt )-RChild ); 死亡(Bt ); * Bt=空值; 返回; }voidinitq(queue*q ) ) {q-front=q-rear=0; }statusenterq(queue*q,QueueElementType x ) if ) (q-rear1) % maxsize==q-front ) return 0; q-ele[q-rear]=x; q-rear=(q-rear1) % maxsize; 返回确定; }statusdeleteq(queue*q,QueueElementType* x ) if ) q-front==q-rear ) return 0; *x=q-ele[q-front]; q-front=(q-front1) % maxsize; //更新团队领导指针return 1; }状态isempty (queue * q ) if ) q-front==q-rear ) return 1; elsereturn 0; }voiddestroyq(queue*q ) if ) q!=空() free ) ) q; q=NULL; }else {printf ('此队列为空! 无法进行破坏操作! n '; }Statuslayorder(bitreeBt ) {Queue* q; BiTree p; q=(queue* ) malloc ) sizeof (queue ); if(q ) initq ) q; if(Bt==null ) return 0; 企业(q,bt ); while (! isempty(q ) ) deleteq,p ); printf('%c ',p-data ); if(p-LChild ) EnterQ(q ) q,p-lchild; if(p-RChild ) EnterQ(q ) q,p-rchild; }返回1; }else {printf ('空间申请失败! n '; }destroyq(q; }voidprinttree(bitreeBt,int nLayer )/*纵向树状打印的二叉树的nLayer表示所在层数(/(//即中序的逆序输出if(Bt==null ) return; 打印树(Bt-rchild,nLayer 1); //访问右边的子树for (inti=0; i nLayer; I ) printf (' ); printf(%c(n )、bt-data ); 打印树(Bt-lchild,nLayer 1); }intmain((bitnode*Bt=) bitnode * (malloc ) sizeof ) bitnode ); createbitree(Bt; printf (层序排列为(n ); layorder(Bt; printf((n ); printf (垂直打印结果(n ); 打印树(Bt,1; 死亡(Bt ); 返回0; }测试用例1 :

测试案例2 :

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。