每日一练之判断一棵树是否是平衡二叉树

判断一棵树是否是平衡二叉树

OJ 地址:判断一棵树是否是平衡二叉树
在这里插入图片描述

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int height(TreeNode *root)
    {
        if(root == NULL)
        {
            return 0;
        }
        int leftDepth = height(root->left);
        int rightDepth = height(root->right);

        return leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1;
    }
    bool isBalanced(TreeNode* root) {
        if(root == NULL)
        {
            return true;
        }
        int leftDepth = height(root->left);
        int rightDepth = height(root->right);

        return abs(leftDepth - rightDepth) <= 1 && isBalanced(root->left) && isBalanced(root->right);
    }
};

在这里插入图片描述

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int height(TreeNode *root)
    {
        if(root == nullptr)
            return 0;
        int leftHeight = height(root->left);
        int rightHeight = height(root->right);
        if(leftHeight == -1 || rightHeight == -1 || abs(leftHeight - rightHeight) > 1)
            return -1;
        else
            return max(leftHeight, rightHeight) + 1;
    }
    bool isBalanced(TreeNode* root) {
        return height(root) >= 0;
    }
};
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页