判断是否为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;
    }
};
相关推荐
丶小鱼丶14 分钟前
数据结构和算法之【阻塞队列】下篇
java·数据结构
wangchunting37 分钟前
数据结构-图
数据结构·算法
6Hzlia1 小时前
【Hot 100 刷题计划】 LeetCode 239. 滑动窗口最大值 | C++ 优先队列与单调队列双解法
数据结构·算法·leetcode
袋鼠云数栈10 小时前
集团数字化统战实战:统一数据门户与全业态监管体系构建
大数据·数据结构·人工智能·多模态
小月球~11 小时前
天梯赛 · 并查集
数据结构·算法
三道渊12 小时前
C语言:文件I/O
c语言·开发语言·数据结构·c++
kali-Myon13 小时前
CTFshow-Pwn142-Off-by-One(堆块重叠)
c语言·数据结构·安全·gdb·pwn·ctf·
计算机安禾14 小时前
【数据结构与算法】第19篇:树与二叉树的基础概念
c语言·开发语言·数据结构·c++·算法·visual studio code·visual studio
寻寻觅觅☆14 小时前
东华OJ-基础题-30-求最晚和最早日期(C++)
数据结构·c++·算法
We་ct17 小时前
LeetCode 295. 数据流的中位数:双堆解法实战解析
开发语言·前端·数据结构·算法·leetcode·typescript·数据流