一:题目:
给定一个二叉树,判断它是否是
平衡二叉树
二:代码:
/**
* 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 account(TreeNode* root){
if(!root) return 0;
int left= account(root->left);
if(left==-1) return -1;
int right= account(root->right);
if(right==-1) return -1;
return abs(left-right)>1?-1:1+max(left,right);
}
bool isBalanced(TreeNode* root) {
return account(root)==-1?false:true;
}
};