判断是否为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;
    }
};
相关推荐
Dlrb121116 小时前
C语言-函数传参
c语言·数据结构·算法
爱滑雪的码农1 天前
Java基础十七:数据结构
数据结构
多加点辣也没关系1 天前
数据结构与算法|第二十三章:高级数据结构
数据结构·算法
孬甭_1 天前
初识数据结构与算法
数据结构
naturerun1 天前
从数组中删除元素的算法
数据结构·c++·算法
酿情师1 天前
区块链原理与技术02:区块链的数据结构04(区块结构)
数据结构·区块链
夏日听雨眠1 天前
数据结构(循环队列)
数据结构·算法·链表
平行侠1 天前
30MacLaren-Marsaglia算法故事文件
数据结构·算法
平行侠1 天前
33水库抽样 - 从未知大小的流中等概率采样
数据结构·算法