为什么三元表达式在if语句正常工作时不更新值?

avwztpqn  于 2021-06-27  发布在  Java
关注(0)|答案(2)|浏览(355)

我还尝试更改三元表达式以产生等效结果:
是否平衡=(数学abs(lh rh)<=1)?true:false;

static boolean is_balanced=true;

public static int balHeight(Node node) {
   if(node==null) return 0;

   int lh  = balHeight(node.left);
   int rh  = balHeight(node.right);

  if(Math.abs(lh-rh)>1) is_balanced = false;
  **// ternary not working here
    // is_balanced = Math.abs(lh-rh) > 1 ? false:true;**

   return Math.max(lh,rh)+1;
}
gdrx4gfi

gdrx4gfi1#

等效代码是 is_balanced = Math.abs(lh - rh) > 1 ? false : is_balanced .
(或者,如果没有三元: is_balanced = is_balanced && Math.abs(lh - rh) <= 1 .)

vcudknz3

vcudknz32#

下面是带三元和不带三元的示例代码,两者产生相同的结果。这意味着三元工作如预期。

public class Test {

  public static void main(String[] args) {
    int lh = 5;
    int rh = 10;
    boolean balanced;
    balanced = Math.abs(lh - rh) > 1;
    System.out.println("General Assignment - " + balanced);
    balanced = Math.abs(lh - rh) > 1 ? true : false;
    System.out.println("Ternary Assignment - " + balanced);
  }
}

输出-

General Assignment - true
Ternary Assignment - true

相关问题