Description
Submission
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode* root) {
bool balanced = true;
dfs(root, balanced);
return balanced;
}
private:
int dfs(TreeNode* root, bool& balanced) {
if(!root) return 0;
int l = dfs(root->left, balanced) + 1;
int r = dfs(root->right, balanced) + 1;
if(abs(r - l) > 1) {
balanced = false;
return 0;
}
return max(l, r);
}
};