【问题标题】:Calculate Balance Factor计算平衡因子
【发布时间】:2013-03-05 23:55:33
【问题描述】:

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

【问题讨论】:

    标签: java binary-tree avl-tree


    【解决方案1】:

    应该很简单:

    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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-29
      • 1970-01-01
      • 1970-01-01
      • 2017-01-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多