【发布时间】:2014-11-13 04:06:30
【问题描述】:
我正在开发一个使用二叉搜索树的项目。这个项目需要我创建一个名为 isBalanced 的方法来检查二叉搜索树是否在容差范围内平衡。我能够弄清楚如何做到这一点,但它非常缓慢。我想知道是否有人有任何技巧可以提高效率。顺便说一句,如果孩子为空,.getLeftChild() 和 .getRightChild() 必须返回 IllegalStateExceptions。我更希望他们亲自返回 null 。
这是我的代码的 sn-p:
@Override
public <T> int getDepth(BinaryTreeNode<T> root) {
return recDepth(root,0);
}
public <T> int recDepth(BinaryTreeNode<T> root,int depth) {
int leftTree,rightTree;
if(!root.hasLeftChild()&&!root.hasRightChild()) return depth;
if(!root.hasLeftChild()) leftTree = 0;
else leftTree = recDepth(root.getLeftChild(),depth+1);
if(!root.hasRightChild()) rightTree = 0;
else rightTree = recDepth(root.getRightChild(),depth+1);
if(rightTree>leftTree) return rightTree;
else return leftTree;
}
@Override
public <T> boolean isBalanced(BinaryTreeNode<T> root, int tolerance) {
if(tolerance<0) throw new IllegalArgumentException("Can't have negative tolerance");
if(root==null) throw new NullPointerException();
return recBalanced(root,tolerance);
}
public <T> boolean recBalanced(BinaryTreeNode<T> root, int tolerance){
try{
if(Math.abs(getDepth(root.getLeftChild())-getDepth(root.getLeftChild()))<=tolerance){
return recBalanced(root.getLeftChild(),tolerance)&&recBalanced(root.getRightChild(),tolerance);
}else return false;
} catch (IllegalStateException e){
if(root.hasLeftChild()&&getDepth(root.getLeftChild())>tolerance-1) return false;
else if(root.hasRightChild()&&getDepth(root.getRightChild())>tolerance-1) return false;
else return true;
}
}
提前感谢您的帮助。
【问题讨论】:
-
我重新格式化了代码以使其更具可读性,但您可以使用条件运算符对其进行改进(我没有这样做,因为我不想使代码变性)
-
对不起,可读性不是很好,感谢编辑。
-
这就是为什么它是评论而不是答案。我已经确定了这段代码效率的原因,并试图向您提出修复建议。
标签: java binary-tree binary-search-tree