我有定义二叉树的Bintree类。 我需要实现一个返回树节点最大位移的方法。 所以返回一对整数;第一个是t的高度,第二个是t的子树的最大不平衡。 “树的不平衡”我的意思是:
树的不平衡 = 左子树的高度与右子树的高度之差的绝对值。
我创建了私有内部类 IntPair 来包含两个整数。 我知道这个方法是一个递归方法,所以我写了基本情况,我认为这是正确的。 相反,我错过了递归步骤...我写的是错的。 如何找到最大值?
public class BinTreeUtil {
protected static class IntPair {
int height;
int maxUnbal;
IntPair(int h, int u) {
height = h;
maxUnbal = u;
}
}
public static int maxUnbalance(BinTree t) {
return heightUnbalance(t).maxUnbal;
}
private static IntPair heightUnbalance(BinTree t) {
if(t == null)
return new IntPair(-1, 0);
else {
int sbil = Math.abs(height(t.left) + height(t.right));
return new IntPair(height(t), ???);
}
}
}
感谢。
答案 0 :(得分:2)
您希望在递归过程中保持高度和不平衡:
private static IntPair heightUnbalance(BinTree t) {
if(t == null)
return new IntPair(0, 0);
else {
IntPair leftResult = heightUnbalance(t.left);
IntPair rightResult = heightUnbalance(t.right);
return new IntPair(1+Math.max(leftResult.height,rightResult.height),
Math.abs(leftResult.height-rightResult.height));
}
}
您希望在递归过程中保持高度和不平衡: