class Solution {
int flag = 1;
public boolean isBalanced(TreeNode root) {
getDepth(root);
return flag == 1? true:false;
}
public int getDepth(TreeNode node){
if(node == null) return 0;
int left = getDepth(node.left);
int right =getDepth(node.right);
if(Math.abs(left - right) > 1) flag = -1;
return Math.max(left,right) + 1;
}
}
自底向上的算法,如果不满足情况则直接把flag置-1,但是还是遍历了二叉树,看了题解后弄个改进版本。
class Solution {
public boolean isBalanced(TreeNode root) {
return getDepth(root) >= 0;
}
public int getDepth(TreeNode node){
if(node == null) return 0;
int left = getDepth(node.left);
int right = getDepth(node.right);
if(Math.abs(left - right) > 1 || left == -1 || right == -1) return -1;
return Math.max(left,right) + 1;
}
}
如果在底下找到不平衡的二叉树了,直接全部返回-1,不计算后续二叉树的高度了。
本文讨论了一种改进的二叉树平衡判断算法,通过自底向上计算节点深度并提前返回-1来避免不必要的遍历。介绍了如何利用flag和早期终止策略提高效率,适用于寻找不平衡节点并快速返回结果。
839

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



