1

我有一个任务,要实现一个打印出二叉树 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;
}
4

1 回答 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;
}
于 2013-03-18T08:05:38.430 回答