平衡二叉树即为树中任意节点的左右两子树高度差不超过1
struct TreeNode
{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int a) :val(a), left(NULL), right(NULL) {};
};
struct rType {
bool isBalanced;
int height;
rType(bool is, int h) :isBalanced(is), height(h) {};
};
rType isbalance(TreeNode * p)
{
if (p == NULL)return rType(true, 0);
rType left = isbalance(p->left);
rType right = isbalance(p->right);
int height = max(left.height, right.height) + 1;//The current tree height is the maximum of left and right subtree height plus 1
bool isbBalanced = left.isBalanced&&right.isBalanced && (abs(left.height - right.height) < 2);
return rType(isbBalanced, height);
}
bool isBalancedTree(TreeNode * p)//main()
{
return isbalance(p).isBalanced;
}