平衡二叉树的判断(左右子树的高度差只能为-1,0,1)
#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);
}
}
bool
IsBalanceTree(BTree tree
){
if(!tree
)
return true
;
int leftDepth
=getDepth(tree
->lchild
);
int rightDepth
=getDepth(tree
->rchild
);
if(abs(leftDepth
-rightDepth
)>1)
return false
;
else{
return IsBalanceTree(tree
->lchild
)&&IsBalanceTree(tree
->rchild
);
}
}
int main(){
printf("二叉树的建立\n");
BTree tree
;
tree
=CreateTree();
printf("二叉树的层序遍历\n");
LayeredOrderTravel(tree
);
printf("\n判断是否为平衡二叉树\n");
bool flag
=IsBalanceTree(tree
);
if(flag
)
printf("该树为平衡二叉树\n");
else
printf("该树为非平衡二叉树\n");
return 0;
}
转载请注明原文地址:https://blackberry.8miu.com/read-41634.html