// 二叉树可以分为普通二叉树,搜索二叉树(排序二叉树),平衡二叉树,完全二叉树,满二叉树
// 搜索二叉树满足所有左子树的值都不大于根节点,所有右子树的值都不小于根节点,并且左右子树也都是搜索二叉树
// 平衡二叉树指左右子树的深度差不大于1
// 完全二叉树首先是一颗平衡二叉树,且满足所有叶子节点在最后最后两层,且最后一层的叶子节点靠左排列
// 满二叉树首先是一颗完全二叉树,且满足节点个数为2^n - 1
typedef struct binary_tree_node
{
int value;
BINARY_TREE_NODE* left;
BINARY_TREE_NODE* right;
} BINARY_TREE_NODE;
int is_balance_binary_tree(BINARY_TREE_NODE *root)
{
if (!root)
{
return -1;
}
int depth = 0;
return check_balance_binary_tree(root, depth);
}
int check_balance_binary_tree(BINARY_TREE_NODE *root, int &depth)
{
if (root == nullptr)
{
depth = 0;
return 0;
}
int left_depth = 0;
int right_depth = 0;
if (check_balance_binary_tree(root->left, left_depth) >=0
&& check_balance_binary_tree(root->left, right_depth) >=0)
{
if (left_depth - right_depth > 1 || left_depth - right_depth < -1)
{
return false;
}
if (left_depth > right_depth)
{
depth = left_depth + 1;
}
else
{
depth = right_depth + 1;
}
}
return -1;
}
int binary_tree_depth(BINARY_TREE_NODE* root)
{
if (!root)
{
return 0;
}
int left = binary_tree_depth(root->left);
int right = binary_tree_depth(root->right);
if (left > right)
{
return left + 1;
}
else
{
return right + 1;
}
}
版权声明:本文为weixin_41402349原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。