层次遍历与树的宽度非递归算法求解此处用到了< queue >为C++语言STL的队列库,其操作原理与队列相同。
#include<stdio.h>
#include<stdlib.h>
#include<queue>
#include <iostream>
#define MAXSIZE 10010
#define ElemType int
using namespace std
;
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 LayeredOrderTravel(BTree tree
){
queue
<BTree
> queue1
;
BTree p
;
if(tree
){
queue1
.push(tree
);
while(!queue1
.empty()){
p
=queue1
.front();
queue1
.pop();
printf("%d ",p
->data
);
if(p
->lchild
)
queue1
.push(p
->lchild
);
if(p
->rchild
)
queue1
.push(p
->rchild
);
}
}
}
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 getWidth2(BTree tree
){
if(!tree
)
return 0;
queue
<BTree
> queue1
;
BTree p
;
int maxWidth
=1,lastWidth
=0,templateWidth
=0;
if(tree
){
queue1
.push(tree
);
lastWidth
=1;
while(!queue1
.empty()){
templateWidth
=lastWidth
;
while(templateWidth
){
p
=queue1
.front();
queue1
.pop();
if(p
->lchild
)
queue1
.push(p
->lchild
);
if(p
->rchild
)
queue1
.push(p
->rchild
);
templateWidth
--;
}
int nowWidth
=queue1
.size();
maxWidth
= nowWidth
> maxWidth
? nowWidth
: maxWidth
;
lastWidth
= nowWidth
;
}
}
return maxWidth
;
}
int main(){
printf("二叉树的建立\n");
BTree tree
;
tree
=CreateTree();
printf("二叉树的层序遍历\n");
LayeredOrderTravel(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
);
printf("\n非递归算法获取二叉树宽度\n");
maxWidth
=getWidth2(tree
);
printf("树的宽度为:%d\n",maxWidth
);
return 0;
}
转载请注明原文地址:https://blackberry.8miu.com/read-39312.html