判断是否为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;
    }
};
相关推荐
疯狂打码的少年4 小时前
【数据结构】交换类排序:冒泡与快速排序
数据结构·笔记·算法·排序算法
Nil2084 小时前
leetcode 108有序数组转换为二叉搜索树
数据结构·算法·leetcode
hn小菜鸡4 小时前
LeetCode 763、划分字母区间
数据结构·算法·leetcode
疯狂打码的少年5 小时前
【数据结构】哈希表:构造与冲突处理
数据结构·笔记·哈希算法·散列表
淡海水6 小时前
03-02-线性-List-T-动态数组布局-扩容与操作成本
数据结构·windows·c#·list·编译·clr·机器码
小飞学编程...15 小时前
【哈希表】
数据结构·哈希算法·散列表
重生之后端学习18 小时前
283. 移动零[简单]✅
开发语言·数据结构·算法·leetcode·职场和发展
动词ing19 小时前
【C语言】结构体+文件基础
c语言·开发语言·数据结构
晚风醉蝶21 小时前
1-11-奇偶排序-OddEvenSort
java·数据结构·算法
旖旎夜光21 小时前
LeetCode 852:山脉数组的峰顶索引(二分查找) —— 题解
数据结构·c++·算法·leetcode·二分查找