判断是否为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;
    }
};
相关推荐
python_chai5 分钟前
Python核心数据结构详解:元组、集合与字典
java·数据结构·python
爱编程的王小美12 分钟前
8876行详解数据结构,从入门到入坟
数据结构
柃歌4 小时前
【LeetCode Solutions】LeetCode 136 ~ 140 题解
数据结构·算法·leetcode
杰瑞学AI5 小时前
LeetCode详解之如何一步步优化到最佳解法:21. 合并两个有序链表
数据结构·python·算法·leetcode·链表·面试·职场和发展
WG_176 小时前
图的储存+图的遍历
数据结构·算法
MPCTHU7 小时前
线性方程组的解法
数据结构·算法
技术小白Byteman10 小时前
蓝桥刷题note13(排序)
开发语言·数据结构·c++·学习·算法·visualstudio
_星辰大海乀10 小时前
二叉树相关练习--2
java·开发语言·数据结构·算法·链表·idea
梭七y11 小时前
【力扣hot100题】(064)在排序数组中查找元素的第一个和最后一个位置
数据结构·算法·leetcode
Protein_zmm12 小时前
[数据结构]图krusakl算法实现
数据结构·算法