📄 node.java
字号:
//
// Group 5
//
import java.lang.*;
import java.util.*;
public class Node {
static final int NUMBER = 0, OPERATOR = 1; // values for kind.
int kind; // type of node.
double number; // The value in a node.
char op; // The operator in a node.
Node left; // left node.
Node right; // right node.
Node(double val) {
// Constructor for making a node of type NUMBER.
kind = NUMBER;
number = val;
}
Node(char val) {
kind = OPERATOR;
this.op = val;
}
Node(Node left, char op, Node right) {
// Constructor for making a node of type OPERATOR.
kind = OPERATOR;
this.op = op;
this.left = left;
this.right = right;
}
// Return the value of the expression.
static double getValue( Node node ) {
if ( node.kind == NUMBER) {
return node.number;
}
else {
double leftVal = getValue( node.left );
double rightVal = getValue( node.right );
switch(node.op) {
case '+': return leftVal + rightVal;
case '-': return leftVal - rightVal;
case '*': return leftVal * rightVal;
case '/': return leftVal / rightVal;
default: return Double.NaN; // return Not a Number.
}
}
}
public static void main (String[] args){
Node t5 = new Node(4);
Node t6 = new Node(9);
Node t7 = new Node(5);
Node t8 = new Node(3);
Node t9 = new Node(4);
Node t4 = new Node(t8, '*', t9);
Node t2 = new Node(t4, '+', t5);
Node t3 = new Node(t6, '-', t7);
Node t1 = new Node(t2, '/', t3);
double value = getValue(t1); // get Value.
System.out.println("Result = " + value); // show value.
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -