判断是否为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;
    }
};
相关推荐
xys_6783 小时前
深挖数据结构:树和二叉树(上)
数据结构·算法
BeiGuTing_code3 小时前
Java动态数组(一)
java·数据结构·windows
Code_Solitude7 小时前
传智杯备赛代码整理(前4题)
数据结构·算法
Jasmine_llq7 小时前
《P8816 [CSP-J 2022] 上升点列》
数据结构·算法·贪心·排序·二维动态规划 dp·类背包状态转移
辛苦才能8 小时前
C++ 哈希表深度解析:删除为什么必须打标记,负载因子为什么卡 0.7
开发语言·数据结构·c++·算法
JasmineX-18 小时前
数据结构(笔记)——顺序栈
c语言·数据结构·笔记
凉茶钱10 小时前
list:哨兵节点,const_iterator 和 const iterator的区别与迭代器失效
数据结构·c++·list
敲代码的苦1311 小时前
头歌数据结构-排序的实现及其应用
数据结构
有同事要进步12 小时前
Leecode第68题:x的平方根
java·数据结构·算法
Pniubi12 小时前
HashMap扩容全流程
java·开发语言·数据结构