Day 66: Python 이진 트리 반전, 완벽한 트리 대칭을 위한 재귀적 미러 스와프 (LeetCode #226 스타일)

발행: (2025년 12월 17일 오전 02:03 GMT+9)
3 min read
원문: Dev.to

Source: Dev.to

Welcome to Day 66 of the #80DaysOfChallenges journey! This intermediate challenge focuses on inverting a binary tree by recursively swapping left and right children, transforming the structure into its mirror image while preserving values. It uses recursive traversal to flip subtrees, a fundamental technique for tree manipulations like symmetry checks or balancing. If you’re advancing from basic recursion to tree algorithms or prepping for interviews (LeetCode #226), this “Python invert binary tree” script demonstrates a function that’s elegant, in‑place, and easy to adapt for iterative versions.

💡 Key Takeaways from Day 66: Tree Inversion Function

1. Function Design: Recursive Swap and Base Case

def invert_tree(tree: dict, node):
    """Recursively invert the binary tree starting from the given node."""
    if node is None:
        return

    left, right = tree.get(node, (None, None))   # get left and right children
    tree[node] = (right, left)                   # swap children

    invert_tree(tree, left)   # invert left subtree
    invert_tree(tree, right)  # invert right subtree
  • 기본 사례는 nodeNone일 때 반환합니다.
  • 자식 노드는 dict.get으로 가져오며 기본값은 (None, None)입니다.
  • 튜플을 교환한 뒤 함수가 두 서브트리 모두에 재귀 호출됩니다.
  • 복잡도: 시간 O(n), 공간 O(h) (여기서 h는 트리 높이).

2. Tree Structure: Dict‑Based Representation

tree = {
    "A": ("B", "C"),
    "B": ("D", "E"),
    "C": (None, "F"),
    "D": (None, None),
    "E": (None, None),
    "F": (None, None),
}
  • 키는 노드 식별자이며, 값은 (left_child, right_child) 튜플입니다.
  • 커스텀 노드 클래스를 사용하지 않는 작은 트리에 간단하고 편리합니다.

3. Main Demo: Before/After Inversion

root = "A"                    # root of the tree

print("Original tree:")
print(tree)

invert_tree(tree, root)       # invert the tree in‑place

print("\nInverted tree:")
print(tree)
  • 출력은 루트의 자식이 교환된 것을 보여줍니다 (A("C", "B")가 되며) 이 변환이 모든 서브트리에 재귀적으로 적용됩니다.

🎯 Summary and Reflections

  • 재귀 패턴: 기본 사례 → 처리(교환) → 자식 재귀 호출.
  • 트리용 딕셔너리: 클래스 기반 노드가 필요 없을 때 유연한 표현.
  • 제자리(in‑place) 수정: 추가 메모리 할당을 피합니다.

가능한 확장으로는 스택이나 큐를 이용한 반복 버전, 혹은 원본과 반전된 구조를 비교해 트리 대칭성을 확인하는 용도가 있습니다.

🚀 Next Steps and Resources

Back to Blog

관련 글

더 보기 »

Leetcode 39 조합 합

문제 설명: 서로 다른 정수들로 이루어진 배열 candidates와 정수 target이 주어지면, 선택된 숫자들의 합이 target이 되는 candidates의 모든 고유한 조합을 반환한다.

순열 & 다음 순열

소개 Permutation은 문제 해결 및 데이터 구조(PS/DSA)에서 기본적인 개념입니다. 재귀, 백트래킹, 조합론, 그래프 등에서 나타납니다.

트리 기본: 구조, 용어, 및 사용 사례

트리란 무엇인가? 트리는 노드들로 구성된 계층적이며 비선형적인 데이터 구조이다. 각 노드: - 값을 저장한다 - 0개 이상의 자식을 가진다 - 정확히 하나의 부모를 가진다

학습 여정을 기록하는 27일 차

오늘 배운 것 - dict 생성자를 사용하고 중괄호 {} 로 딕셔너리를 정의하는 방법. - .get 메서드를 사용해 딕셔너리의 요소에 접근하는 방법.