오늘 배웠습니다: 이진 트리 반전

문제 설명



이진 트리를 가져와 반전시키는 함수를 작성하십시오.

샘플 입력



tree =      1
          /   \
        2       3
      /   \   /   \
     4    5  6     7
   /   \
  8     9

샘플 결과



tree =      1
          /   \
        3       2
      /   \   /   \
     7    6  5     4
                 /   \
                9     8

코드 #1



def invert_binary_tree(tree):
    queue = [tree]
    while len(queue) > 0:
        cur_node = queue.pop(0)
        if cur_node is not None: 
            cur_node.left, cur_node.right = cur_node.right, cur_node.left
            queue.append(cur_node.left)
            queue.append(cur_node.right)
    return tree


# This is the class of the input binary tree.
class BinaryTree:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

메모


  • 먼저 트리의 루트 노드를 반전시킵니다.
  • Invert = 왼쪽 자식을 오른쪽 자식으로 바꿉니다.
  • 후속 노드의 자식을 계속 교환합니다.
  • 너비 우선 순회를 수행합니다.
  • 순회를 반복적으로 수행하려면 대기열을 활용하십시오.

  • 크레딧


  • 문제 진술에 대한 Algoexpert.
  • 표지 이미지의 토마스 로버트슨(https://unsplash.com/photos/wAKld_0lcmA ).
  • 좋은 웹페이지 즐겨찾기