剑指 Offer 55 - II. 平衡二叉树 - 力扣(LeetCode)
类似题:LeetCode第 110 题:平衡二叉树(C++)_zj-CSDN博客
自上而下(存在大量重复计算:需要同时计算其子树高度,所以最下面的节点会被计算很多次高度):
class Solution {
public:
bool isBalanced(TreeNode* root) {
if(!root) return true;
return isBalanced(root->left) && isBalanced(root->right) && abs(height(root->left)-height(root->right)) < 2;
}
int height(TreeNode *root){
if(!root) return 0;
return 1+ max(height(root->left), height(root->right));
}
};
自下而上:
class Solution {
public:
bool isBalanced(TreeNode* root) {
return help(root) != -1;
}
int help(TreeNode *root){
if(!root) return 0;
int left = help(root->left);
if(left == -1) return -1;
int right = help(root->right);
if(right == -1) return -1;
return abs(left-right) < 2 ? max(left, right)+1 : -1;//当左右子树平衡时向上返回深度
}
};