判断是否为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;
    }
};
相关推荐
XW9632585 小时前
除湿机行业组织能力与人才地图报告
大数据·服务器·网络·数据结构·数据库·人工智能
风落青芜8 小时前
排序算法(四):归并排序、计数排序与算法总结
c语言·开发语言·数据结构·算法·排序算法
老师我太想进步了202615 小时前
【数据结构-15】实现链式结构二叉树
c语言·数据结构
xiangxueCode17 小时前
数据结构:容器适配器之优先级队列
数据结构·优先级队列
鱼很腾apoc18 小时前
【Redis】第2期 详解Redis五大数据结构:命令+C++实现、渐进式遍历与数据库管理
linux·服务器·c语言·数据结构·c++·redis·学习
让我们一起加油好吗2 天前
【数据结构】线段树详解
数据结构·c++·算法·线段树·洛谷
路灯中转站2 天前
数据结构C语言版(什么是数据类型)
数据结构
凌冰_2 天前
数据结构 - 队列(五)
数据结构·算法·软件工程
让我们一起加油好吗2 天前
【数据结构】ST 表
数据结构·c++·算法·动态规划·洛谷·st表
让我们一起加油好吗2 天前
【算法刷题】LeetCode 力扣 Hot 100 刷题记录
数据结构·c++·算法·leetcode·面试·笔试