Java 计算平衡系数
我有一个任务,来实现一个方法,它打印出二叉树t的所有内部节点的平衡因子 我已经试过了,但我需要三种方法。。我认为应该有一个,我只能打印出根的平衡因子,我认为这应该是树t的每个节点的平衡因子Java 计算平衡系数,java,binary-tree,avl-tree,Java,Binary Tree,Avl Tree,我有一个任务,来实现一个方法,它打印出二叉树t的所有内部节点的平衡因子 我已经试过了,但我需要三种方法。。我认为应该有一个,我只能打印出根的平衡因子,我认为这应该是树t的每个节点的平衡因子 public int maxHeight(BinaryTree t) { if(t == null) { return 0; } int height1 = maxHeight(t.getLeft()) + 1; int height2 = maxH
public int maxHeight(BinaryTree t) {
if(t == null) {
return 0;
}
int height1 = maxHeight(t.getLeft()) + 1;
int height2 = maxHeight(t.getRight()) + 1;
if(height1 > height2) {
return height1;
}
else {
return height2;
}
}
public int minHeight(BinaryTree v) {
if(v == null) {
return 0;
}
int height1 = minHeight(v.getLeft()) + 1;
int height2 = minHeight(v.getRight()) + 1;
if(height1 < height2) {
return height1;
}
else {
return height2;
}
}
public int balanceFactor(int max, int min) {
return max - min;
}
public int maxHeight(二进制树t){
如果(t==null){
返回0;
}
int height1=maxHeight(t.getLeft())+1;
int height2=maxHeight(t.getRight())+1;
如果(高度1>高度2){
返回高度1;
}
否则{
返回高度2;
}
}
公共整数最小高度(二叉树v){
如果(v==null){
返回0;
}
int height1=minHeight(v.getLeft())+1;
int height2=minHeight(v.getRight())+1;
如果(高度1<高度2){
返回高度1;
}
否则{
返回高度2;
}
}
公共整数平衡因子(整数最大值,整数最小值){
返回最大-最小值;
}
它应该简单到:
public int printBalanceFactor(BinaryTree t)
{
if (t == null)
return 0;
if (t.left == null && t.right == null)
return 1;
int heightL = printBalanceFactor(t.left);
int heightR = printBalanceFactor(t.right);
System.out.println("Balance factor of " + t + " is " + (heightL - heightR));
return heightL + heightR + 1;
}