코드 목적은 이진 표현 트리를 평가하는 것입니다 (아래처럼). 내가 가지고있는 코드에서 이진 표현 트리에서 누락 된 피연산자 확인
(+)
(*) (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
* 누락 된 피연산자를 어떻게 확인합니까? 리프 노드 (피연산자) 인 경우 if 조건이 참이므로 예외가 발생합니까? "* Um ... 예? 잎 노드에 왼쪽 또는 오른쪽 형제가 없다고 가정 할 때, 아마도'getLeft'와'getRight'는'null'을 반환합니다. 그래서 코드는 예외를 throw합니다. 기대하지 않는 것은 무엇입니까? –
리프 노드 인 경우 계속 실행해야합니다. 하나의 리프 노드 만 피연산자라면 피연산자로 두 개의 리드 노드가 필요하므로 예외가 발생합니다. 나는? 나는 그것이 여기에서 어떻게 작동하는지에 관해 오히려 혼란 스럽다. .. 내가 그것을 아주 분명히 설명하지 않으면 사과한다. – user3735871
@ user : * "하나의 리프 노드 만 피연산자 인 경우 피연산자로 두 개의 리드 노드가 필요하므로 예외가 발생합니다."* 코드가 사용하는 이유는'||'("OR")를 사용하기 때문입니다. . 그래서 만약'root.getLeft() == null' 또는'root.getRight() =='null''을 의미하면'(root.getLeft() == null || root.getRight() == null) (예외를 throw하는) 블록에서 비트를 수행하십시오. –