#include<algorithm>
#include<vector>
using namespace std;
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
class Solution {
public:
pair<bool, int>dfs(TreeNode* root) {
if (root == NULL)
return make_pair(true, 0);
auto[left_balanced, left_h] = dfs(root->left);
auto[right_balances, right_h] = dfs(root->right);
return make_pair(left_balanced&&right_balances&&abs(left_h - right_h) <= 1, 1 + max(left_h, right_h));
}
bool IsBalanced_Solution(TreeNode* pRoot) {
if (pRoot == NULL)
return true;
auto [left_balanced, left_h] = dfs(pRoot->left);
auto[right_balances, right_h] = dfs(pRoot->right);
if (left_balanced&&right_balances&& abs(left_h - right_h) <= 1)
return true;
else
return false;
}
};