方法一:(笨办法,把每一个结点的两个子树深度作差,判断是否小于1,进行深度优先遍历判断,貌似复杂度比较高)
class Solution {
public:
int getDepth(TreeNode *root){
if(root==NULL)
return 0;
if(root->left==NULL&&root->right==NULL)
return 1;
int l=0, r=0;
if(root->left!=NULL)
l=1+getDepth(root->left);
if(root->right!=NULL)
r=1+getDepth(root->right);
return max(l,r);
}
bool isBalanced(TreeNode *root) {
if(root==NULL)
return true;
return abs(getDepth(root->left)-getDepth(root->right))<=1&&isBalanced(root->left)&&isBalanced(root->right);
};
};
方法二:(少嵌套一个dfs,每次递归计算深度的时候就进行差值比较,一旦不满足小于等于1就标记一个特殊值-1, 比较奇怪的是这个方法跑出来时间比上一个方法还要长...)
class Solution {
public:
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
int getDepth(TreeNode *root){
if(root==NULL)
return 0;
if(root->left==NULL&&root->right==NULL)
return 1;
int l=0, r=0;
if(root->left!=NULL)
l=getDepth(root->left);
if(root->right!=NULL)
r=getDepth(root->right);
if(l==-1||r==-1||abs(l-r)>1)
return -1;
return max(l,r)+1;
}
bool isBalanced(TreeNode *root) {
return getDepth(root)!=-1;
};
};