2014-06-17 5 views
0

코드 목적은 이진 표현 트리를 평가하는 것입니다 (아래처럼). 내가 가지고있는 코드에서 이진 표현 트리에서 누락 된 피연산자 확인

  (+) 
     (*)  (2) 
    (+)  (-) 
3 4 5 2 

, 내가없는 피연산자 방법 if (root.getLeft() == null || root.getRight() == null) 검사에 대한 혼란 스러워요. 리프 노드 (피연산자) 인 경우 예외가 발생합니다 (if 조건이 true 일 때)? 또한 질문을 if 문 근처의 코드에 주석으로 추가합니다. 내가 제거 의견이있는 경우 문까지 코드를 가지고 아래

public float calculateValue(TreeNode root) { 
    // Check that the root value is not null 
    if (root == null) { 
    throw new IllegalArgumentException("Root Node must have a value"); 
    } 
    // If this is a leaf node, it should be a number, so return this 
    if (root.getLeft() == null && root.getRight() == null) { 
    try { 
     return Float.parseFloat(root.getItem().toString()); 
    } catch (NumberFormatException parseError) { 
     throw new NumberFormatException("Leaves must be numeric"); 
    } 
    } 
    // Validate that we have operands 
    if (root.getLeft() == null || root.getRight() == null) {  
    // How does this check for missing operands? If it is a leaf node (operand), 
    // will it cause an exception (as the if condition will be true)? 
    throw new IllegalArgumentException("Operator missing operands”); 
    } 
    // Retrieve the operands 
    float leftOperand = calculateValue(root.getLeft()); 
    float rightOperand = calculateValue(root.getRight()); 
    // Extract the operator 
    String operatorString = root.getItem().toString(); 
    if (operatorString.length() > 1) { 
    throw new IllegalArgumentException("Invalid operation!"); 
    } 
    char operator = operatorString.charAt(0); 
    // Evaluate the operation 
+0

* 누락 된 피연산자를 어떻게 확인합니까? 리프 노드 (피연산자) 인 경우 if 조건이 참이므로 예외가 발생합니까? "* Um ... 예? 잎 노드에 왼쪽 또는 오른쪽 형제가 없다고 가정 할 때, 아마도'getLeft'와'getRight'는'null'을 반환합니다. 그래서 코드는 예외를 throw합니다. 기대하지 않는 것은 무엇입니까? –

+0

리프 노드 인 경우 계속 실행해야합니다. 하나의 리프 노드 만 피연산자라면 피연산자로 두 개의 리드 노드가 필요하므로 예외가 발생합니다. 나는? 나는 그것이 여기에서 어떻게 작동하는지에 관해 오히려 혼란 스럽다. .. 내가 그것을 아주 분명히 설명하지 않으면 사과한다. – user3735871

+1

@ user : * "하나의 리프 노드 만 피연산자 인 경우 피연산자로 두 개의 리드 노드가 필요하므로 예외가 발생합니다."* 코드가 사용하는 이유는'||'("OR")를 사용하기 때문입니다. . 그래서 만약'root.getLeft() == null' 또는'root.getRight() =='null''을 의미하면'(root.getLeft() == null || root.getRight() == null) (예외를 throw하는) 블록에서 비트를 수행하십시오. –

답변

0

:

if (root == null) { 
    throw new IllegalArgumentException("Root Node must have a value"); 
} 

if (root.getLeft() == null && root.getRight() == null) { 
    try { 
     return Float.parseFloat(root.getItem().toString()); 
    } catch (NumberFormatException parseError) { 
     throw new NumberFormatException("Leaves must be numeric"); 
    } 
} 

if (root.getLeft() == null || root.getRight() == null) {  
    throw new IllegalArgumentException("Operator missing operands"); 
} 

은, 귀하의 질문에 대답 잎 노드의 경우 점에 유의하기 위해, 만약 두 번째 - 진술은 사실입니다. 따라서, 그것은 try-catch를 통과 할 것이고 결코 실행하지 않을 것이다 if (root.getLeft() == null || root.getRight() == null).

+0

@ user3735871 이제 답변을 얻으십시오. 예를 들어, try-catch , 당신은 "return Float.parseFloat ..."를 아무런 문제없이 던지거나 Exception을 던질 것이지만, 당신은 세번째 if 문으로 가지 않을 것입니다. –