先来介绍一下平衡二叉树。两个条件:
- 它的左子树和右子树的深度之差(平衡因子)的绝对值不超过1
-
它的左子树和右子树都是一颗平衡二叉树。
今天就先写如何判断是否平衡二叉树;判断算法也是基于以上两个条件,除了满足左右子树的高度之差不能大于1之外还要在判断左右子树是不是平衡二叉树。有这种情况:
这是题目链接,https://leetcode-cn.com/problems/check-balance-lcci/,AC代码如下:
class Solution {
public:
int height(TreeNode* root){
if(root==NULL) return 0;
return max(height(root->left),height(root->right))+1;
}
bool isBalanced(TreeNode* root) {
if(root==NULL) return true;
if(abs(height(root->left)-height(root->right))>1) return false;
else{
return isBalanced(root->left) && isBalanced(root->right);
}
}
};