递归当时参考了一下网上的,没有严格测试,目前存在点问题,复习紧张,有空了再更,见谅。这是非递归版本。(正确的)https://blog.csdn.net/weixin_42468092/article/details/108961202 -二叉树的深度与宽度的计算(递归版本) 示例:(A)1,(B)2,0,(C)3,0,0,(D)4,0,0
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define MAXSIZE 10010
#define ElemType int
typedef struct BTNode
{
ElemType data
;
BTNode
*lchild
,*rchild
;
}*BTree
;
BTree
CreateTree(){
ElemType ch
;
printf("输入结点元素值:");
scanf("%d",&ch
);
if(ch
== 0)
return NULL;
else{
BTree tree
=(BTree
)malloc(sizeof(BTree
));
tree
->data
=ch
;
printf("%d 结点左子树\n",ch
);
tree
->lchild
=CreateTree();
printf("%d 结点右子树\n",ch
);
tree
->rchild
=CreateTree();
return tree
;
}
}
void PreOrderTravel(BTree tree
){
if(tree
== NULL)
return;
printf("%d ",tree
->data
);
PreOrderTravel(tree
->lchild
);
PreOrderTravel(tree
->rchild
);
}
void MedOrderTravel(BTree tree
){
if(tree
== NULL)
return;
MedOrderTravel(tree
->lchild
);
printf("%d ",tree
->data
);
MedOrderTravel(tree
->rchild
);
}
void AftOrderTravel(BTree tree
){
if(tree
== NULL)
return;
AftOrderTravel(tree
->lchild
);
AftOrderTravel(tree
->rchild
);
printf("%d ",tree
->data
);
}
int getDepth(BTree tree
){
if(!tree
)
return 0;
else{
int leftDepth
=getDepth(tree
->lchild
);
int rightDepth
=getDepth(tree
->rchild
);
return leftDepth
> rightDepth
? (leftDepth
+1):(rightDepth
+1);
}
}
int getWidth(BTree tree
){
if(!tree
)
return 0;
int maxWidth
=0;
if(!tree
->lchild
&& !tree
->rchild
) {
return 1;
}else{
maxWidth
=(getWidth(tree
->lchild
)+getWidth(tree
->rchild
)) > maxWidth
? (getWidth(tree
->lchild
)+getWidth(tree
->rchild
)) : maxWidth
;
}
return maxWidth
;
}
int main(){
printf("二叉树的建立\n");
BTree tree
;
tree
=CreateTree();
printf("二叉树的先序遍历\n");
PreOrderTravel(tree
);
printf("\n获取二叉树深度\n");
int maxDepth
=0,maxWidth
=0;
maxDepth
=getDepth(tree
);
printf("树的深度为:%d\n",maxDepth
);
printf("\n获取二叉树宽度\n");
maxWidth
=getWidth(tree
);
printf("树的宽度为:%d\n",maxWidth
);
return 0;
}
转载请注明原文地址:https://blackberry.8miu.com/read-32968.html