Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
topic:
Solution:
direct violence to obtain highly about sub-tree, and then compare the difference in height but also about recursion tree to determine whether the child is balanced binary tree
code show as below:
class Solution {
public:
//解法1:自顶向下,由于递归会对大量的节点访问和计算,所以时间复杂度最差为O(n^2),空间复杂度为O(1)
bool isBalanced(TreeNode* root) {
if(root==nullptr)return true;
/*else return abs(countFloors(root->left)-countFloors(root->right))<2&&isBalanced(root->left)&&isBalanced(root->right);*/
if(abs(countFloors(root->left)-countFloors(root->right))>1)return false;//左右子树的高度差要小于等于1
else{
if(isBalanced(root->left)&&isBalanced(root->right))return true;//左右子树都是平衡的
return false;
}
}
int countFloors(TreeNode* root)
{
if(root==nullptr)return 0;
else return 1+max(countFloors(root->left),countFloors(root->right));
}
//解法二:自底向上,时间复杂度为O(n),空间复杂度为O(1)
private:
bool result=true;
public:
bool isBalanced(TreeNode* root)
{
helper(root);
return result;
}
int helper(TreeNode* root)
{
if(root==nullptr)return 0;
int left=1+helper(root->left);//计算左子树的深度,或者左右子树中的某颗二叉树的左子树深度
int right=1+helper(root->right);//计算右子树的深度,同左子树
if(abs(left-right)>1)result=false;//高度差大于1表示不是高度平衡二叉树
return max(left,right);//返回的左子树或者右子树中的一个二叉树的左右子树的最大高度
}
};