class Solution {
public boolean isBalanced(TreeNode root) {
if(root == null) return true;
else{
boolean isHeightNear = Math.abs( height(root.left) - height(root.right) ) <=1;
return isHeightNear && isBalanced(root.left) && isBalanced(root.right);
}
}
int height(TreeNode a){
if(a==null) return 0;
else return 1+Math.max(height(a.left),height(a.right));
}
}
直接法:
判断左右节点高度差是否小于1 , 如果是 ,则递归判断左右节点的左右节点是否平衡
时间复杂度O(nlogn)
原因是有两重的递归 重复遍历了
解决方法是在height计算时顺便把是否balance也判断了
class Solution {
public boolean isBalanced(TreeNode root) {
if(root == null) return true;
return heightAndCheckBalance(root)!=-1;
}
int heightAndCheckBalance(TreeNode node){//这个函数,如果发现不平衡则返回-1, 否则会返回高度
if(node==null) return 0;
int leftHeight=heightAndCheckBalance(node.left);
if(leftHeight==-1) { return -1;}
int rightHeight = heightAndCheckBalance(node.right);
if(rightHeight==-1) {return -1;}
if(Math.abs(leftHeight-rightHeight)>1){return -1;}
return 1+Math.max(leftHeight, rightHeight);
}
}
时间复杂度降到O(n)
这篇博客探讨了一种优化平衡二叉树判断的方法,通过修改原有的递归算法,将时间复杂度从O(nlogn)降低到O(n)。博主详细介绍了如何在计算节点高度的同时检查平衡状态,避免了重复遍历,从而提高了算法效率。
467

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



