我有一个赋值,用于实现打印出二叉树t的所有内部节点的平衡因子的方法。
我试过这样做,但我需要三种方法..我认为应该有一种方法而且我只能打印出根的平衡因子,我认为这应该是树t的每个节点?
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;
}
答案 0 :(得分: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;
}