[SWEXPERT] 1232. 사칙연산 (이진트리, C++, D4)

728x90
반응형

사칙연산 유효성 검사 풀고 풀었다가 완전 이진트리로 착각하여 입력을 이상하게 받아

5번 예제부터 자꾸 틀렸다. ㅠㅠ

 

아닌 걸 알고 입력부분 고쳐서 해결함.

연산자를 가지는 노드는 자식이 없고 연산자인 노드만 자식을 추가적으로 입력받는다.

 

나머지는 재귀로 중위 계산해준다.

 

#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include <vector>
#include <string>
using namespace std;

double tree[1001][2];
string oper[1001];

double inorder(int num) {

	if (tree[num][0]) {//자식있음
		double a = inorder(tree[num][0]); //왼쪽 계산
		double b = inorder(tree[num][1]); //오른쪽 계산 
		if (oper[num] == "+")return a + b;
		if (oper[num] == "-")return a - b;
		if (oper[num] == "*")return a * b;
		if (oper[num] == "/")return a / b;
	}
	return stod(oper[num]); //자식없는 친구는 자기자신(수) 리턴
}

int main(void) {

	ios::sync_with_stdio(false);
	cin.tie(NULL);
	
	for (int tc = 1; tc <= 10; tc++)
	{
		int n;
		cin >> n;
		for (int i = 1; i <= n; i++) {
			cin >> i;			
			string ch;//자식없으면 숫자가 들어간다.
			cin >> ch;
			oper[i] = ch;
			if (ch == "+" || ch == "-" || ch == "*" || ch == "/") {//연산자인 애들만 자식있음
				double left, right;
				cin >> left >> right;
				tree[i][0] = left;
				tree[i][1] = right;
			}
			
		}

		int ans=inorder(1);//정수로 자름
		cout << "#" << tc << " " << ans << "\n";

	
	}


	return 0;
}
728x90
반응형
TAGS.

Comments