首先明白平衡二叉树的定义:
它是一 棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树
然后要明白一个结点的高度的定义:
这个节点到其子树中的叶子节点的最长路径的长度;
然后就是递归的写法:
class Solution {
public:
bool isBalanced(TreeNode *root) {
if(!root)
return true;
int l=depth(root->left);
int r=depth(root->right);
if(abs(l-r)<=1){
if(isBalanced(root->left)&&isBalanced(root->right))
return true;
}
return false;
}
int depth(TreeNode *root){
if(!root)
return 0;
return max(depth(root->left),depth(root->right))+1;
}
};
转载请注明原文地址: https://ju.6miu.com/read-1125205.html