难度: 简单
题目:
给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。
解题
自顶向下
从顶向下计算,需要计算每个节点的左右子树高度,并且左右子树各自也要满足平衡,这样在判断左右子树是否平衡时对之前计算过的高度,又重复计算。
class Solution {
public:
int height(TreeNode* root) {
if (root == NULL) {
return 0;
} else {
return max(height(root->left), height(root->right)) + 1;
}
}
bool isBalanced(TreeNode* root) {
if (root == NULL) {
return true;
} else {
return abs(height(root->left) - height(root->right)) <= 1 && isBalanced(root->left) && isBalanced(root->right);
}
}
};
自底向上
自底向上进行判断,每个节点对应的高度只需要计算一次。
class Solution {
public:
bool isBalanced(TreeNode* root) {
return height(root) >= 0;
}
int height(TreeNode *root)
{
if(root == nullptr)
{
return 0;
}
int iLeftHeight = height(root->left);
int iRightHeight = height(root->right);
if(iLeftHeight == -1 || iRightHeight == -1 || abs(iLeftHeight - iRightHeight) >1 )
{
return -1;
}
else
{
return max(iLeftHeight,iRightHeight) + 1;
}
}
};