判断是否为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;
    }
};
相关推荐
琢磨先生David7 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
qq_454245037 天前
基于组件与行为的树状节点系统
数据结构·c#
超级大福宝7 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
岛雨QA7 天前
常用十种算法「Java数据结构与算法学习笔记13」
数据结构·算法
weiabc7 天前
printf(“%lf“, ys) 和 cout << ys 输出的浮点数格式存在细微差异
数据结构·c++·算法
wefg17 天前
【算法】单调栈和单调队列
数据结构·算法
岛雨QA7 天前
图「Java数据结构与算法学习笔记12」
数据结构·算法
czxyvX7 天前
020-C++之unordered容器
数据结构·c++
岛雨QA7 天前
多路查找树「Java数据结构与算法学习笔记11」
数据结构·算法
AKA__Zas7 天前
初识基本排序
java·数据结构·学习方法·排序