본문 바로가기

컴퓨터/코테

백준 1068 - 트리 문제

node = int(input())
parent = [int(x) for x in input().split(' ')]
deleted = int(input())

class Node :
    def __init__(self, data):
        self.data = data
        self.child = []

class Tree :
    def __init__(self, node):
        self.root = node
        self.leaf = 0
    def preorder(self, node):
        for i in node.child :
            if i.data == deleted:
                continue
            self.preorder(i)
        if not node.child or (len(node.child) == 1 and node.child[0].data == deleted):
            self.leaf += 1

nodeList = []
for i in range(node) :
    nodeList.append(Node(i))

for i in range(node) :
    if parent[i] == -1 :
        myTree = Tree(nodeList[i])
        continue
    nodeList[parent[i]].child.append(nodeList[i])

if myTree.root.data == deleted :
    print(0)
else :
    myTree.preorder(myTree.root)
    print(myTree.leaf)