1.给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。
2.代码展示
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int treedeep(struct TreeNode* root)
{
if (root == NULL)
{
return 0;
}
int a = 1+treedeep(root->left);
int b = 1+treedeep(root->right);
return a>b ?a:b;
}
void max(int*p1,int*p2)
{
if (*p2>*p1)
{
int tmp = *p2;
*p2 = *p1;
*p1 = tmp;
}
}
bool isBalanced(struct TreeNode* root)
{
if (root == NULL)
{
return true;
}
int a = treedeep(root->left);
int b = treedeep(root->right);
max(&a,&b);
return (a-b <= 1)&&isBalanced(root->left)&&isBalanced(root->right);
}
3.解题思路
先判断根节点是否为空,为空就遍历它的左右子树,求出左右子树的长度,然后看是否满足条件,满足就继续向下遍历,直到输出。