[SWEA] 사칙연산 Posted on 2020-02-24 | In Problem_Solving | 문제 보러가기 제한사항 이외의 제한사항은 없다. 첫번째 생각 dfs 탐색 방식으로 노드를 탐색하면서 사칙연산을 수행해주도록 한다. JAVA Code 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273import java.util.Scanner; public class Solution { static Node[] node; public static void main(String[] args) { Scanner sc = new Scanner(System.in); for(int tc=1;tc<=10;tc++) { int N = sc.nextInt(); node = new Node[N]; for(int i=0; i<N; i++) { int num = sc.nextInt(); String Data = sc.next(); int left = 0; int right = 0; if (Data.equals("-") || Data.equals("+") || Data.equals("*") || Data.equals("/")) { left = sc.nextInt()-1; right = sc.nextInt()-1; node[i] = new Node(num,Data,left,right); } else { node[i] = new Node(num,Data); } } int ans = go(0); System.out.println("#"+tc+" "+ans); } } public static int go(int index) { if (node[index].left == -1) { return Integer.parseInt(node[index].Data); } node[index].left = go(node[index].left); node[index].right = go(node[index].right); switch(node[index].Data) { case "+": { node[index].Data = (node[index].left+node[index].right)+ ""; break; } case "-": { node[index].Data = (node[index].left-node[index].right)+ ""; break; } case "*": { node[index].Data = (node[index].left*node[index].right)+ ""; break; } case "/": { node[index].Data = (node[index].left/node[index].right)+ ""; break; } } return Integer.parseInt(node[index].Data); } public static class Node { int num; String Data; int left; int right; Node(int num,String Data) { this.num = num; this.Data = Data; this.left = -1; this.right = -1; } Node(int num,String Data, int left, int right) { this.num = num; this.Data = Data; this.left = left; this.right = right; } } }