문제 확인하기
2. 정답 코드 (python3, memory: 31120KB, time: 40ms)
import sys
input = sys.stdin.readline
def remove_node_and_count_leaves(target_node):
tree[target_node] = -2
for i in range(num_nodes):
if target_node == tree[i]:
remove_node_and_count_leaves(i)
num_nodes = int(input())
tree = list(map(int, input().split()))
node_to_remove = int(input())
remove_node_and_count_leaves(node_to_remove)
leaf_node_count = 0
for i in range(num_nodes):
if tree[i] != -2 and i not in tree:
leaf_node_count += 1
print(leaf_node_count)