시작하기무료로 시작하기

책 제목을 알파벳 순으로 출력하기

이 영상에서는 이진 트리에 깊이 우선 탐색(Depth First Search) 순회를 구현하는 세 가지 방식, 즉 중위(in-order), 전위(pre-order), 후위(post-order) 순회를 배웠어요.

아래 이진 탐색 트리에는 여러 책의 제목이 저장되어 있어요.

Graphical representation of a binary search tree.

트리는 bst 변수(15번째 줄)에 미리 로드되어 있습니다:

bst = CreateTree()

책 제목이 알파벳 순으로 나오도록 중위 순회를 적용해 보시겠어요?

이 연습은 강의의 일부입니다

Python으로 배우는 자료구조와 알고리즘

강의 보기

연습 안내

  • current_node가 존재하는지 확인하세요.
  • 트리의 알맞은 하위 부분에 대해 in_order() 함수를 재귀적으로 호출하세요.
  • current_node의 값을 출력하세요.
  • 트리의 다른 하위 부분에 대해 in_order() 함수를 재귀적으로 호출하세요.

실습형 인터랙티브 연습

이 예제를 이 샘플 코드를 완성하여 풀어보세요.

class BinarySearchTree:
  def __init__(self):
    self.root = None

  def in_order(self, current_node):
    # Check if current_node exists
    if ____:
      # Call recursively with the appropriate half of the tree
      self.in_order(current_node.____)
      # Print the value of the current_node
      print(____)
      # Call recursively with the appropriate half of the tree
      self.in_order(current_node.____)
  
bst = CreateTree()
bst.in_order(bst.root)
코드 편집 및 실행