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.
Solution:Code:
<span style="font-size:14px;">/**
* 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 helper(TreeNode *root, int &depth) {
if (!root) {
depth = 0;
return true;
}
int left, right;
if (!helper(root->left, left) || !helper(root->right, right)) return false;
if (abs(left-right) > 1) return false;
depth = max(left, right)+1;
return true;
}
bool isBalanced(TreeNode *root) {
int depth;
return helper(root, depth);
}
};</span>