Skip to content

Commit 2a88983

Browse files
rxdcxdrninettasjwi
authored andcommitted
[Miller] BOJ(1068): 트리 - 문제풀이 추가
1 parent 16c1a63 commit 2a88983

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

src/밀러/BOJ_1068.py

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
from typing import List, Optional
2+
3+
4+
class Node:
5+
def __init__(self, ind: int, parent: int):
6+
self.ind = ind
7+
self.parent = parent
8+
self.children: List[int] = []
9+
10+
def add_child(self, child):
11+
self.children.append(child)
12+
13+
def __str__(self):
14+
children: List[str] = [str(child) for child in self.children]
15+
return "Node(ind=" + str(self.ind) \
16+
+ ", parent=" + str(self.parent) \
17+
+ ", children=[" + ", ".join(children) + "])"
18+
19+
20+
class Integer:
21+
def __init__(self, val: int = 0):
22+
self.val = val
23+
24+
25+
def solution(nums: List[int], delete: int):
26+
nodes: List[Node] = [Node(ind, parent) for ind, parent in enumerate(nums)]
27+
leafs = Integer()
28+
29+
for node in nodes:
30+
if node.parent == -1:
31+
continue
32+
nodes[node.parent].add_child(node.ind)
33+
34+
def dfs(parent: Optional[int], ind: int):
35+
if ind == delete:
36+
if parent is not None \
37+
and len(nodes[parent].children) == 1:
38+
leafs.val += 1
39+
return
40+
41+
if not nodes[ind].children:
42+
leafs.val += 1
43+
44+
for child in nodes[ind].children:
45+
dfs(ind, child)
46+
return
47+
48+
root: Optional[int] = None
49+
for node in nodes:
50+
if node.parent == -1:
51+
root = node.ind
52+
53+
dfs(None, root)
54+
return leafs.val
55+
56+
57+
if __name__ == "__main__":
58+
N: int = int(input())
59+
nums: List[int] = list(map(int, input().split()))
60+
delete: int = int(input())
61+
62+
print(solution(nums, delete))

0 commit comments

Comments
 (0)