判断是否为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;
    }
};
相关推荐
Fanxt_Ja3 小时前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
今后1235 小时前
【数据结构】二叉树的概念
数据结构·二叉树
散11217 小时前
01数据结构-01背包问题
数据结构
消失的旧时光-194317 小时前
Kotlinx.serialization 使用讲解
android·数据结构·android jetpack
Gu_shiwww18 小时前
数据结构8——双向链表
c语言·数据结构·python·链表·小白初步
苏小瀚19 小时前
[数据结构] 排序
数据结构
睡不醒的kun21 小时前
leetcode算法刷题的第三十四天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
吃着火锅x唱着歌21 小时前
LeetCode 978.最长湍流子数组
数据结构·算法·leetcode
Whisper_long1 天前
【数据结构】深入理解堆:概念、应用与实现
数据结构
IAtlantiscsdn1 天前
Redis7底层数据结构解析
前端·数据结构·bootstrap