后序遍历即可
class Solution {
bool flag = true;
public:
int getHeight(TreeNode* root)
{
if(!root) return 0;
int l_h = getHeight(root->left), r_h = getHeight(root->right); // 左右子树高度
if(abs(l_h - r_h) > 1) flag = false;
return max(l_h, r_h) + 1; // 返回的高度要+1
}
bool isBalanced(TreeNode* root) {
getHeight(root);
return flag;
}
};
代码缺点:未进行剪枝