首页 > 编程知识 正文

使用二叉链表实现二叉树的基本操作

时间:2023-05-04 09:35:32 阅读:159128 作者:4749

# include stdio.h # include stack # define maxsize 100 usingnamespacestd; int count1=0; int count2=0; typedef struct BiNode{char data; //数据域struct BiNode *lchild,*rchild; //左右子树指针}BiTNode,*BiTree; //先横移成两股,ABC##de#g##f###(#表示树是空的) voidcreatebtree(bitreet ) ) {char ch; scanf('%c ',ch ); if(ch=='# ' ) {T=NULL; }else{T=new BiNode; T-data=ch; 创建树(t-lchild ); 创建树(t-rchild ); }//先遍历二叉树的递归方法voidtravebitreefirstroot (bitreet ) if ) t ) ) printf ) ' %c ',T-data ); travebitreefirstroot(t-lchild; travebitreefirstroot(t-rchild; }/*复制二叉树申请新节点,复制根节点; 递归复制左树; 递归复制右子树。 */voidcopybitree(bitreet,BiTree NewT ) if ) t==null ) {NewT=NULL; 返回; }NewT=new BiNode; NewT-data=T-data; copybitree(t-lchild,NewT-lchild ); copybitree(t-rchild,NewT-rchild ); (/*树深度是树的节点的最大层次,树的深度在树的左右子树的深度的最大值上加1 )对于空树,深度为0; m是子树的深度。n是右边的子树的深度。树的深度为m和n中的最大值1*/intdepth(bitreet ) {int m=0; int n=0; if(t==null ) {return 0; }m=Depth(t-Lchild ); n=Depth(t-Rchild ); return mn? (m 1 ) 3360 ) n1 ); (/)统计二叉树的节点数二叉树的节点数=左部分树节点数右部分树节点数1(/intnodecont ) bitreet ) if(t==null ) {return 0; }returnnodecont(t-lchild ) node cont (t-rchild ) 1; (/)统计二叉树的叶(度0 )节点数如果树为空,则叶节点数为0; 当树上只有根节点时,叶节点数为1; 递归左树; 递归右子树; */intnodecount0(bitreet ) if ) t==null ) {return 0; } if (t-lchild==nullt-rchild==null ) {return 1; } else { return node count0(t-lchild ) node count0(t-rchild ); }/*如果统计二叉树度为1的节点数树为空或仅为根节点,则返回0; 递归左树; 递归右子树; */intnodecount1(bitreet ) if ) t==null ) {return 0; (if ) (t-lchild! T-Rchild(||! t-lchildt-rchild (} { count1=count 1; }nodecount1(t-lchild ); nodecount1(t-rchild ); (/*计数二叉树度为2的节点数)如果只有空树或根节点,则返回0; 递归左树; 递归右子树; */intnodecount2(bitreet ) if ) t==null ) {return 0; }if(t-lchildt-rchild ) ) {count2=count2 1; }nodecount2(t-lchild ); nodecount2(t-rchild ); (} int main ) ) {BiTree T; 输入printf ()二叉树的节点,按照最初遍历的顺序,输入双重链表:(n ) ); 创建树(t; printf (二叉树:(n ); travebitreefirstroot(t; 打印((n ); BiTree NewT; copybitree(t,NewT ); printf (复制的二叉树:(n ); travebitreefirstroot(newt; 打印((n ); intdepth=depth(t; printf (树深:%d(n ),depth ); intnodecount=nodecont(t; printf (二叉树节点数:%d(n ),nodeCount ); intcount0=nodecount0(t; printf (二叉树叶节点数:%d(n ),count0); 节点计数1 (t; printf (二叉树中度为1的节点数:%d(n ),count1); //int count2=0; 节点计数2 (t; printf (二叉树中度为2的节点数:%d(n ),count2); }

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