/**
* 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 getHeight(TreeNode* root) {
if(root == nullptr) return 0;
int lefthigh = getHeight(root->left);
if(lefthigh == -1) return -1;
int righthigh = getHeight(root->right);
if(righthigh == -1) return -1;
return abs(lefthigh - righthigh) > 1 ? -1 : 1 + max(lefthigh, righthigh);
}
bool isBalanced(TreeNode* root) {
return getHeight(root) != -1;
}
};
力扣110. 平衡二叉树
最新推荐文章于 2025-04-07 18:31:44 发布