题目描述:输入一颗二叉树,判断该二叉树是否是平衡二叉树。
思路:平衡二叉树是指左右子树高度差不超过1,空树是平衡二叉树,平衡二叉树的左右子树也是平衡二叉树。
(所以对于一个二叉树,可以计算其左右子树的高度,如果高度差大于1,那么则将子树高度设为-1;如果高度差小于等于1,那么这个子树是一个平衡二叉树,返回这个子树的高度。)直接看程序吧
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
return BalancedHeight(pRoot) >= 0;
}
int BalancedHeight(TreeNode* root)
{
if(root == nullptr)
return 0;
int left = BalancedHeight(root->left);
int right = BalancedHeight(root->right);
if(left < 0 || right < 0 || abs(left - right) > 1)
return -1;
return max(left, right) + 1;
}
};