practivceAlgorithm/swexpertacademy

[SWEA][Python] 1232 사칙연산

findTheValue 2021. 9. 23. 23:43

중위순횐줄 알았는데 제대로보니 중위는 아니고. 그냥 말단부터 올라오는 분할정복.

 

import sys
sys.stdin = open('input.txt')


def inorder_tree(cur_node):
    if not tree[cur_node]:
        return int(values[cur_node])
    left = inorder_tree(tree[cur_node][0])
    right = inorder_tree(tree[cur_node][1])
    if values[cur_node] == '-':
        return left - right
    elif values[cur_node] == '+':
        return left + right
    elif values[cur_node] == '*':
        return left * right
    else:
        return left / right


for test in range(1, 11):
    N = int(input())
    tree = {i: [] for i in range(1, N+1)}
    values = {i: '' for i in range(1, N+1)}
    for _ in range(N):
        data = input().split()
        values[int(data[0])] = data[1]
        if len(data) == 3:
            tree[int(data[0])] += [int(data[2])]
        elif len(data) == 4:
            tree[int(data[0])] += [int(data[2])]
            tree[int(data[0])] += [int(data[3])]

    answer = int(inorder_tree(1))
    print(f'#{test} {answer}')

'practivceAlgorithm > swexpertacademy' 카테고리의 다른 글

[SWEA][Python] 1952 수영장  (0) 2021.09.24
[SWEA][Python] 1949 등산로 조성  (0) 2021.09.24
[SWEA][Python] 1231 중위순회  (0) 2021.09.23
[SWEA][Python] 5186 이진수2  (0) 2021.09.19
[SWEA][Python] 5185 이진수  (0) 2021.09.19