首页 > 编程知识 正文

二叉树的三种遍历,树的先根序列和后根序列

时间:2023-05-03 18:55:00 阅读:14211 作者:3973

利用树的先后顺序和中序构建二叉树。

# include stdio.h # include stdlib.htypedefintelement _ type; typedefstructnode { element _ typedata; 结构节点*Rson,*Rson; }节点,*ptr; ptrcreat1(element_typea (,element_type b[] )、int i、int j、int s、int t ) {int k; PTR; if(ij )返回空值; p=(ptr ) malloc(sizeof ) node ); p-data=a[i]; k=s; while () k=t ) ) b[k]!=a[i] () k; if(b[k]!=a[i] )退出(0); p-LSON=creat1(a、b、i 1、i k-s、s、k-1 ); p-rson=creat1(a,b,i k-s 1,j,k 1,t ); 返回p; }voidpreorder_1(ptrp ) /超前遍历(printf )、p-data ); if(p-LSON!=null(preorder_1) p-LSON; if(p-rson!=null(preorder_1) p-rson ); }voidpreorder_2(ptrp ) /中序扫描) if(p-LSON!=null(preorder_2) p-LSON; printf('%d ',p-data ); if(p-rson!=null(preorder_2) p-rson ); }voidpreorder_3(ptrp ) /后行遍历) if(p-LSON!=null(preorder_3) p-LSON; if(p-rson!=null(preorder_3) p-rson ); printf('%d ',p-data ); }voidpreorder_4(ptrp ) /层序遍历(if ) p==null )返回; int front=-1,rear=0; ptr queue[100]; 队列[ rear ]=p; wile (前端!=rear}{front; printf('%d ',queue[front]-data ); if(queue[front]-LSON!=null}{rear; queue[rear]=queue[front]-Lson; (if ) queue [前]-rson!=null}{rear; queue[rear]=queue[front]-Rson; }}}int main () {ptr root; element_type a[100],b[100]; int N,i=0,j=0,s=0,t=0; printf ('请输入树的节点数:'); scanf('%d ',n ); printf ('请输入树的第一个序列:'); for (; jN; j ) Scanf('%d ',a[j]; printf ('请输入树的中顺序序列:'); for (; tN; t ) Scanf('%d ',b[t]; root=creat1(a、b、I、j-1、s、t-1 ); printf (树优先级); preorder _1(根); printf((n ); printf ('树的中序序列:'); preorder _2(根); printf((n ); printf ('树后序列:'); preorder _3(根; printf((n ); printf (木层序序列); preorder _4(根; }

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