- 先求出以每个结点为根的树的高度
- 如果不满足平衡二叉树的定义,则返回-1;满足则返回高度。
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
#include <complex>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pRoot TreeNode类
* @return bool布尔型
*/
bool IsBalanced_Solution(TreeNode* pRoot) {
// write code here
if (pRoot == nullptr) {
return true;
}
return depth(pRoot) == -1?false:true;
}
private:
int depth(TreeNode* root) {
if (root == nullptr) {
return 0;
}
int ldep = depth(root->left);
if (ldep == -1) return -1;
int rdep = depth(root->right);
if (rdep == -1) return -1;
if (abs(ldep - rdep) >1) {
return -1;
}else {
return max(ldep,rdep) +1;
}
}
};