// 求二叉树的高度函数 nullptr为0 然后累加 +1 return left-right
// 结论都还是递归 当前状态 多加了一个递归求高度 双重递归
class Solution {
public:
//求二叉树的高度
int height(TreeNode * root)
{
if(root == nullptr) return 0;
TreeNode * left = root->left;
TreeNode * right = root->right;
return max(height(left)+1,height(right)+1);
}
//递归判断
bool isBalanced(TreeNode* root) {
if(root == nullptr) return true;
if(fabs(height(root->left) - height(root->right)) <= 1)
{
return isBalanced(root->left) && isBalanced(root->right);
}
else return false;
}
};
49 - 算法 - LeetCode 110 平衡二叉树 - 求二叉树的高度 -双重递归
最新推荐文章于 2023-02-07 20:48:49 发布