判断一个二叉树是否平衡
判断二叉树是否平衡的方法是求左右儿子的深度相差是否大于1,大于则这个二叉树不平衡.
class Solution { public: int height(TreeNode *root) {//求节点的高度 if(root == NULL)return 0; return max(height(root->left), height(root->right)) + 1; } bool isBalanced(TreeNode* root) { if(root == NULL)return true; return isBalanced(root->left) && isBalanced(root->right) && abs(height(root->left) - height(root->right)) <= 1; } };