Checking for missing operands in a binary expression tree

expression-trees java

Question

The purpose of the code is to perform the evaluation of binary expression trees (like the one below).

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

In the code snippet I have, I am confused about how if (root.getLeft() == null || root.getRight() == null) checks for missing operands. If it is a leaf node (operand), will it cause an exception (as the if condition will be true)? I also put the question as a comment in the code near the if-statement.

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

Accepted Answer

Below I've got your code up to that if-statement with the comments removed:

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

To answer your question, note that in the case of a leaf node, the second if-statement is true. Thus, it will go through that try-catch and never even execute if (root.getLeft() == null || root.getRight() == null).



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow