判断是否为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;
    }
};
相关推荐
minji...9 分钟前
算法---模拟/高精度/枚举
数据结构·c++·算法·高精度·模拟·枚举
代码村新手17 分钟前
数据结构-二叉树
数据结构
姓蔡小朋友18 分钟前
redis GEO数据结构、实现附近商铺功能
数据结构·数据库·redis
Live&&learn1 小时前
数据结构vs 内存结构
数据结构·操作系统·内存结构
buyue__1 小时前
C++实现数据结构——队列和栈
数据结构
太理摆烂哥1 小时前
哈希表实现
数据结构·哈希算法·散列表
Kuo-Teng9 小时前
LeetCode 279: Perfect Squares
java·数据结构·算法·leetcode·职场和发展
CoderYanger10 小时前
B.双指针——3194. 最小元素和最大元素的最小平均值
java·开发语言·数据结构·算法·leetcode·职场和发展·1024程序员节
SalvoGao10 小时前
Python学习 | 怎么理解epoch?
数据结构·人工智能·python·深度学习·学习
兩尛14 小时前
215. 数组中的第K个最大元素
数据结构·算法·排序算法