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:
bool checkBalanced(TreeNode *node, int &depth) {
if(node == NULL) {
depth = 0;
return true;
}
int leftdep, rightdep;
bool leftBalance = checkBalanced(node->left, leftdep);
bool rightBalance = checkBalanced(node->right, rightdep);
depth = max(leftdep, rightdep) + 1;
return leftBalance && rightBalance && (abs(rightdep - leftdep) <= 1);
}
bool isBalanced(TreeNode *root) {
int depth;
return checkBalanced(root, depth);
}
};