检查二进制表达式树中缺少的操作数

时间:2014-06-17 23:44:01

标签: java expression-trees

代码的目的是执行二进制表达式树的评估(如下所示)。

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

在我的代码片段中,我对if (root.getLeft() == null || root.getRight() == null)如何检查缺少的操作数感到困惑。如果它是叶节点(操作数),它是否会导致异常(因为if条件为真)?我还把问题作为注释放在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

1 个答案:

答案 0 :(得分:0)

下面我已经将您的代码添加到删除了注释的if语句:

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

要回答您的问题,请注意,对于叶节点,第二个if语句为true。因此,它将通过try-catch,甚至不执行if (root.getLeft() == null || root.getRight() == null)