判斷二叉樹是否平衡的方法是求左右兒子的深度相差是否大於1,大於則這個二叉樹不平衡.spa
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; } };