#include <stdio.h>
#include <cmath>
//二叉树结点
typedef struct binary_tree_node_t{
binary_tree_node_t * left;
binary_tree_node_t * right;
int elem;
};
//方法1:
//按照后序遍历的顺序,判断左右子树,同时得到左右子树的深度;再检查当前结点的左右子树深度差是否不大于1
bool isBalanced(binary_tree_node_t * root, int * depth){//传参一个int指针,可直接修改一个int值
if(root == NULL){
*depth = 0;
return true;
}
int leftDepth, rightDepth;
if(isBalanced(root->left, &leftDepth) && isBalanced(root->right, &rightDepth)){
if( abs(leftDepth - rightDepth) <= 1){
*depth = leftDepth > rightDepth ? leftDepth+1 : rightDepth+1;//同时求出当前结点的深度!!!
return true;
}
}
return false;
}
//方法2:
//求子树的最大深度和最小深度之差
int maxDepth(binary_tree_node_t * root){
if(root == NULL){
return 0;
}
return maxDepth(root->left) > maxDepth(root->right) ? maxDepth(root->left)+1 : maxDepth(root->right)+1;
}
int minDepth(binary_tree_node_t * root){
if(root == NULL){
return 0;
}
return minDepth(root->left) < minDepth(root->right) ? minDepth(root->left)+1 : minDepth(root->right)+1;
}
bool isBalanced2(binary_tree_node_t * root){
int diff = abs(maxDepth(root) - minDepth(root));
return diff<=1;
}
//判断一颗二叉树是不是平衡二叉树
int main(){
binary_tree_node_t ns[10];
for(int i = 1; i <= 7; i++){
binary_tree_node_t tmp;
tmp.elem = i;
tmp.left = NULL;//必须显式初始化为NULL
tmp.right = NULL;
ns[i] = tmp;
}
binary_tree_node_t root;
root.left = NULL;
root.right = NULL;
root.elem = 4;
root.left = &ns[2];
root.right = &ns[5];
ns[2].left = &ns[1];
ns[2].right = &ns[3];
ns[5].right = &ns[6];
int depth = 0;
printf("%d\n",isBalanced(&root, &depth)?1:0);
//printf("%d\n",isBalanced2(&root)?1:0);
return 0;
}
转载于:https://my.oschina.net/kaneiqi/blog/308872