判断是否为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;
    }
};
相关推荐
萌の鱼1 小时前
leetcode 2826. 将三个组排序
数据结构·c++·算法·leetcode
Buling_01 小时前
算法-哈希表篇08-四数之和
数据结构·算法·散列表
左灯右行的爱情4 小时前
Redis数据结构总结-listPack
数据结构·数据库·redis
fai厅的秃头姐!4 小时前
C语言03
c语言·数据结构·算法
醉城夜风~4 小时前
[数据结构]单链表详解
数据结构·链表
myprogramc4 小时前
十大排序算法
数据结构·算法·排序算法
计算机小白一个4 小时前
蓝桥杯 Java B 组之岛屿数量、二叉树路径和(区分DFS与回溯)
java·数据结构·算法·蓝桥杯
孤雪心殇5 小时前
简单易懂,解析Go语言中的Map
开发语言·数据结构·后端·golang·go
柃歌5 小时前
【UCB CS 61B SP24】Lecture 7 - Lists 4: Arrays and Lists学习笔记
java·数据结构·笔记·学习·算法
柃歌6 小时前
【UCB CS 61B SP24】Lecture 4 - Lists 2: SLLists学习笔记
java·数据结构·笔记·学习·算法