每个节点 的左右两个子树的高度差的绝对值不超过1:显然就是递归了。
自上而下递归
如果左右子树均平衡并且高度差不超过1,则平衡:
初始代码:
class Solution {
public:
int height(TreeNode* root){
if(!root) return -1;
return max(height(root->left), height(root->right)) + 1;
}
bool isBalanced(TreeNode* root) {
if(!root) return true;
return isBalanced(root->right) && isBalanced(root->left) && abs(height(root->left) - height(root->right)) < 2;
}
};
自下而上递归
第一个方法计算 height 时有大量重复计算:需要同时计算其子树高度,所以最下面的节点会被计算很多次高度。
但自底向上计算,每个子树的高度只会计算一次,计算之后在向上传递用于计算上一层节点的高度。所以我们可以递归先计算当前节点的子节点高度,通过子节点高度判断当前节点是否平衡,再考虑上一层的节点。
class Solution {
public:
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;
}
bool isBalanced(TreeNode* root) {
return help(root) != -1;
}
};