判断一棵树是否是平衡二叉树
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;
}
};