[S/W 문제해결 기본] 사칙연산 (D4)
문제 링크
Solution
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
class Node {
String data;
int leftChild;
int rightChild;
public Node(String data) {
this.data = data;
}
}
public class Solution {
static Node[] nodes;
public static float calc(Node node) {
if(node.leftChild != 0) {
float x = calc(nodes[node.leftChild]);
float y = calc(nodes[node.rightChild]);
String operator = node.data;
return operation(operator, x, y);
}
return Integer.parseInt(node.data);
}
public static float operation(String op, float x, float y) {
switch(op) {
case "+":
return x+y;
case "-":
return x-y;
case "*":
return x*y;
case "/":
return x/y;
}
return -1;
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer stk;
int N;
for(int t=1; t<=10; t++) {
N = Integer.parseInt(br.readLine());
nodes = new Node[N+1];
for(int i=0; i<N; i++) {
stk = new StringTokenizer(br.readLine(), " ");
int nowNodeIdx = Integer.parseInt(stk.nextToken());
nodes[nowNodeIdx] = new Node(stk.nextToken());
if(stk.hasMoreElements()) {
nodes[nowNodeIdx].leftChild = Integer.parseInt(stk.nextToken());
nodes[nowNodeIdx].rightChild = Integer.parseInt(stk.nextToken());
}
}
System.out.printf("#%d %d\n", t, (int) calc(nodes[1]));
}
}
}