/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int maxHeight(TreeNode* root)
{
if(!root)
{
return 0;
}
int l_height=maxHeight(root->left);
int r_height=maxHeight(root->right);
return ((l_height>r_height)?(l_height+1):(r_height+1));
}
bool isBalanced(TreeNode* root) {
if(!root)
{
return true;
}
if(abs(maxHeight(root->left)-maxHeight(root->right))<=1)//(maxHeight(root->left)==maxHeight(root->right)||maxHeight(root->left)==maxHeight(root->right)+1||maxHeight(root->left)==maxHeight(root->right)-1)
{
return isBalanced(root->left)*isBalanced(root->right);
}
return false;
}
};
110.平衡二叉树
最新推荐文章于 2023-04-04 15:44:51 发布