思想:
每一节点的左支和右支的深度和不能超过1;
每一节点(作为它父节点的左支或右支)都有一个深度值要返回,以便在其父节点进行平衡判断;
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode *root) {
if(balancedHeight(root) >= 0) return true;
else return false;
}
int balancedHeight(TreeNode *root) {
if(root == NULL) return true;
int left = balancedHeight(root->left);
int right = balancedHeight(root->right);
if(left < 0 || right < 0 || abs(left-right) > 1)
return -1;
return max(left,right)+1;
}
};