Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 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:
int max,min;
bool subDepth(TreeNode* p,int& d){
if(!p) return true;
int l=d+1,r=d+1;
bool result=subDepth(p->left,l)&&subDepth(p->right,r)&&(abs(l-r)<=1);
d=l>r?l:r;
return result;
}
bool isBalanced(TreeNode *root) {
int depth=0;
return subDepth(root,depth);
}
};