https://leetcode.com/problems/balanced-binary-tree/description/
/**
* 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:
int maxDepth(TreeNode* root, int currDepth) {
int left_depth = (root->left == nullptr) ? currDepth : maxDepth(root->left, currDepth + 1);
int right_depth = (root->right == nullptr) ? currDepth : maxDepth(root->right, currDepth + 1);
if (left_depth == -1 || right_depth == -1)
return -1;
if (left_depth - right_depth > 1 ||
right_depth - left_depth > 1)
return -1;
return max(left_depth, right_depth);
}
bool isBalanced(TreeNode* root) {
if (root == nullptr)
return true;
if (maxDepth(root, 0) == -1)
return false;
return true;
}
};