判断是否为AVL树

leetcode题目链接

自顶向下的递归

cpp 复制代码
class Solution {
public:
    bool isBalanced(TreeNode* root) {
        if(root)
            return abs(maxDepth(root->left) - maxDepth(root->right)) <= 1 && isBalanced(root->left) && isBalanced(root->right);
        return true;
    }
    int maxDepth(TreeNode* root){
        if(root)
            return max(maxDepth(root->left),maxDepth(root->right)) + 1;
        return 0;
    }
};

自底向上的递归

cpp 复制代码
class Solution {
public:
    bool isBalanced(TreeNode* root) {
        return height(root) >= 0;
    }

    int height(TreeNode* root){
        if(root == NULL)
            return 0;
        int l = height(root->left);
        int r = height(root->right);
        if( l == -1 || r == -1 || abs(l - r) > 1)
            return -1;
        return max(l,r) + 1;
    }
};
相关推荐
罗超驿3 小时前
2.算法效率的核心密码:时间复杂度和空间复杂度详解
java·数据结构·算法
:-)4 小时前
算法-堆排序
数据结构·算法·排序算法
j7~7 小时前
【数据结构初阶】顺序表增删查改代码实现--详解
数据结构·顺序表·动态顺序表·静态顺序表
枕星而眠7 小时前
【数据结构】红黑树入门指南
运维·数据结构·c++·后端
:-)9 小时前
基础算法-选择排序
数据结构·算法·排序算法
粘稠的浆糊9 小时前
[AtCoder - abc465_d ]X to Y题解
数据结构·c++·算法
海清河晏1119 小时前
数据结构 | 二叉平衡搜索树
开发语言·数据结构·visual studio
兰令水10 小时前
hot100【acm版】【2026.7.11/12打卡-java版本】
java·开发语言·数据结构·算法·职场和发展
叩码以求索11 小时前
使用next数组加速匹配过程
java·数据结构·算法
小欣加油12 小时前
leetcode1331 数组序号转换
数据结构·c++·算法·leetcode·职场和发展