트리의 모든 노드의 합을 구해야 할 때 클래스를 생성하고 루트 노드를 설정하고 트리에 요소를 추가하고 특정 요소를 검색하고 트리의 요소를 추가하는 메소드를 포함합니다. 합계 등을 찾습니다. 이러한 메서드에 액세스하고 사용하기 위해 클래스의 인스턴스를 만들 수 있습니다.
아래는 동일한 데모입니다 -
예시
from collections import deque
def add_edge(v, w):
global visited_node, adj
adj[v].append(w)
adj[w].append(v)
def BFS_operation(component_num, src):
global visited_node, adj
queue = deque()
queue.append(src)
visited_node[src] = 1
reachableNodes = []
while (len(queue) > 0):
u = queue.popleft()
reachableNodes.append(u)
for itr in adj[u]:
if (visited_node[itr] == 0):
visited_node[itr] = 1
queue.append(itr)
return reachableNodes
def displayReachableNodes(m):
for i in m:
print(i, end = " ")
print()
def findReachableNodes(my_list, n):
global V, adj, visited_node
a = []
component_num = 0
for i in range(n):
u = my_list[i]
if (visited_node[u] == 0):
component_num += 1
a = BFS_operation(component_num, u)
print("The reachable nodes from ", u, " are")
displayReachableNodes(a)
V = 7
adj = [[] for i in range(V + 1)]
visited_node = [0 for i in range(V + 1)]
add_edge(1, 2)
add_edge(2, 3)
add_edge(3, 4)
add_edge(3, 1)
add_edge(5, 6)
add_edge(5, 7)
my_list = [ 2, 4, 5, 7 ]
arr_len = len(my_list)
findReachableNodes(my_list, arr_len) 출력
The reachable nodes from 2 are 2 1 3 4 The reachable nodes from 4 are 2 1 3 4 The reachable nodes from 5 are 5 6 7 The reachable nodes from 7 are 5 6 7
설명
-
필요한 패키지를 가져옵니다.
-
트리에 요소를 추가하는 데 도움이 되는 'add_edge'라는 메서드가 정의되어 있습니다.
-
'BFS_operation' 방법은 너비 우선 탐색 접근 방식을 사용하여 트리를 탐색하는 데 도움이 됩니다.
-
특정 노드에서 도달할 수 있는 노드를 표시하는 데 도움이 되는 'displayReachableNodes'라는 메서드가 정의되어 있습니다.
-
노드를 반복하고 요소에 대해 'BFS_operation'을 수행하는 'findReachableNodes'라는 메서드가 정의되어 있습니다.
-
'add_edge' 메소드는 그래프에 노드를 추가합니다.
-
목록이 정의되어 콘솔에 표시됩니다.
-
메소드가 호출되고 출력이 콘솔에 표시됩니다.