判断是否为AVL树

leetcode题目链接

自顶向下的递归

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;
    }
};

自底向上的递归

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;
    }
};

你可能感兴趣的:(二叉树,数据结构)