PHpullh
학습 라이브러리/Python/트리와 그래프

PYTHON · 컬렉션

트리와 그래프

Python으로 트리와 그래프 자료구조를 구현하고 순회하는 방법입니다.

컬렉션고급tree트리graph그래프BFS

핵심 설명

Python으로 트리와 그래프 자료구조를 구현하고 순회하는 방법입니다.

Python code

from collections import defaultdict, deque

# 이진 트리
class TreeNode:
    def __init__(self, val, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

# 트리 순회
def inorder(node):
    if node:
        yield from inorder(node.left)
        yield node.val
        yield from inorder(node.right)

root = TreeNode(4,
    TreeNode(2, TreeNode(1), TreeNode(3)),
    TreeNode(6, TreeNode(5), TreeNode(7)))

print("중위:", list(inorder(root)))  # [1, 2, 3, 4, 5, 6, 7]

# 그래프 (인접 리스트)
graph = defaultdict(list)
edges = [("A","B"), ("A","C"), ("B","D"), ("C","D"), ("D","E")]
for u, v in edges:
    graph[u].append(v)
    graph[v].append(u)

# BFS
def bfs(graph, start):
    visited = {start}
    queue = deque([start])
    order = []
    while queue:
        node = queue.popleft()
        order.append(node)
        for neighbor in graph[node]:
            if neighbor not in visited:
                visited.add(neighbor)
                queue.append(neighbor)
    return order

print("BFS:", bfs(graph, "A"))  # ['A', 'B', 'C', 'D', 'E']

학습 팁

yield from을 사용한 트리 순회는 재귀보다 메모리 효율적입니다.

주의할 점

그래프에서 visited 체크를 빠뜨리면 사이클이 있을 때 무한 루프에 빠집니다.

자주 묻는 질문

트리와 그래프란 무엇인가요?

Python으로 트리와 그래프 자료구조를 구현하고 순회하는 방법입니다.

트리와 그래프 학습 시 주의할 점은 무엇인가요?

그래프에서 visited 체크를 빠뜨리면 사이클이 있을 때 무한 루프에 빠집니다.

Continue Learning

Python 학습을 이어가세요

총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.