백준 1068 트리 파이썬 풀이
정답 코드
# BOJ 1068 트리 # 2022 06 23 08:39 - 09:12 import sys input = sys.stdin.readline def main(): v = int(input()) graph = [[] for _ in range(v) ] connection = list(map(int,input().split())) root = -2 for idx, value in enumerate(connection): if value == -1: root = idx else: graph[value].append(idx) deleteNode = int(input()) if deleteNode == root : print(0) return # print(graph) parentNode = connection[deleteNode] graph[parentNode].remove(deleteNode) graph[deleteNode]=[] # print(graph) leaf = 0 def dfs(cur): nonlocal leaf for next in graph[cur]: if graph[next]: dfs(next) else: leaf+=1 return if not graph[root]: print(1) return dfs(root) print(leaf) # [[2], [], [], [], []] # [[1], [3, 4], [], [], []] main()
핵심 풀이
- 노드를 삭제 할 때, 부모에서 한 번, 자식노드 삭제 총 두 번 해줘야 한다.
- 방문배열을 따로 만들 필요가 없다.
- 루트를 삭제할 경우와, 하나뿐인 루트의 자식을 삭제할 경우 예외처리를 해줘야 한다.
'PS > BOJ' 카테고리의 다른 글
백준 1240번 노드 사이의 거리 파이썬 풀이 (0) | 2022.06.22 |
---|---|
백준 1039번 교환 파이썬 풀이 (0) | 2022.06.08 |
백준 1713 후보 추천하기 (0) | 2022.05.26 |
백준 1062 가르침 파이썬 풀이 (0) | 2022.05.26 |
백준 1759 암호만들기 C++ (0) | 2022.02.18 |
댓글
이 글 공유하기
다른 글
-
백준 1240번 노드 사이의 거리 파이썬 풀이
백준 1240번 노드 사이의 거리 파이썬 풀이
2022.06.22 -
백준 1039번 교환 파이썬 풀이
백준 1039번 교환 파이썬 풀이
2022.06.08 -
백준 1713 후보 추천하기
백준 1713 후보 추천하기
2022.05.26 -
백준 1062 가르침 파이썬 풀이
백준 1062 가르침 파이썬 풀이
2022.05.26
댓글을 사용할 수 없습니다.