1.题目

2.分析和解答
class Solution {
public boolean isBalanced(TreeNode root) {
// 从子结点开始判断,
if(judge(root) != -1){
return true;
}else{
return false;
}
}
public int judge(TreeNode node){
if(node == null){
return 0;
}
int left = judge(node.left);
int right = judge(node.right);
// 如果等于-1,说名不平衡,直接返回
if(left == -1 || right == -1){
return -1;
}
// 判断两个高度之差是否<=1
if(Math.abs(left - right) <= 1){
return left > right ? left+1 : right+1;
}else{
return -1;
}
}
}
时间复杂度O(n), 因为会遍历每个结点,空间复杂度为树的高度O(d)
535



被折叠的 条评论
为什么被折叠?



