Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

BFS 순회를 사용하여 트리 및 디스플레이의 미러 복사본을 만드는 Python 프로그램

<시간/>

트리의 미러 복사본을 만들고 너비 우선 검색을 사용하여 표시해야 하는 경우 루트 요소를 설정하고, 요소를 왼쪽에 삽입하고, 요소를 오른쪽에 삽입하고, 특정 요소를 검색하고, 주문 후 순회 등을 수행합니다. 클래스의 인스턴스가 생성되고 메서드에 액세스하는 데 사용할 수 있습니다.

아래는 동일한 데모입니다 -

class BinaryTree_struct:def __init__(self, key=None):self.key =key self.left =None self.right =None def set_root(self, key):self.key =key def insert_to_left(self, new_node ):self.left =new_node def insert_to_right(self, new_node):self.right =new_node def search_elem(self, key):self.key ==key인 경우:self.left가 None이 아니면 반환 self:temp =self. left.search_elem(key) temp가 아닌 경우 None:self.right가 아닌 경우 temp를 반환 None:temp =self.right.search_elem(key) 반환 temp return None def copy_mirror(self):mirror =BinaryTree_struct(self.key) self.right가 None이 아닌 경우:mirror.left =self.right.copy_mirror() self.left가 None이 아닌 경우:mirror.right =self.left.copy_mirror() return mirror def bfs(self):queue =[self ] while queue !=[]:popped =queue.pop(0) popped.left가 None이 아닌 경우:queue.app end(popped.left) popped.right가 None이 아닌 경우:queue.append(popped.right) print(popped.key, end=' ')my_instance =Noneprint('메뉴(중복 키가 없다고 가정)')print( '루트에  삽입')print(' 왼쪽에  삽입')print(' 오른쪽에  삽입')print('mirror')print('quit')while True:my_input =input('어떤 작업을 하시겠습니까? ').split() 작업 =my_input[0].strip().lower() if 작업 =='삽입':데이터 =int(my_input[1]) new_node =BinaryTree_struct(data) 하위 작업 =my_input[2]. strip().lower() if suboperation =='at':my_instance =new_node else:position =my_input[4].strip().lower() key =int(position) ref_node =my_instance가 None이 아니면 None:ref_node =my_instance.search_elem(key) if ref_node is None:print('No 그러한 키가 존재하지 않습니다..') 하위 작업 =='left'인 경우 계속:ref_node.insert_to_left(new_node) elif 하위 작업 =='right':ref_node.insert_to_right( new_node) elif 연산 =='mirror':my_instance가 None이 아닌 경우:print('거울 사본 생성 중...') mirror =my_instance.copy_mirror() print('원래 트리의 너비 우선 탐색 순회는 ') my_instance.bfs() print() print('빵 미러의 첫 번째 순회는 다음과 같습니다. ') mirror.bfs() print() elif 작업 =='quit':break

출력

메뉴(중복 키가 없다고 가정)루트에 <데이터> 삽입 <데이터> 왼쪽에 <데이터> 삽입 <데이터>미러 오른쪽에 <데이터> 삽입어떤 작업을 수행하시겠습니까? 루트에 6을 삽입하십시오.어떤 작업을 수행하시겠습니까? insert 9 left of 6어떤 작업을 하시겠습니까? insert 4 right of 6어떤 작업을 하시겠습니까? mirror미러 복사본 생성 중...원래 트리의 너비 우선 탐색 순회는 다음과 같습니다. 6 9 4미러의 너비 우선 탐색은 다음과 같습니다. /사전> 

설명

  • 필수 속성을 가진 'BinaryTree_struct' 클래스가 생성됩니다.

  • 왼쪽과 오른쪽 노드를 'None'에 할당하는 데 사용되는 '초기화' 기능이 있습니다.

  • 루트 노드를 값에 할당하는 데 도움이 되는 'set_root' 메서드가 정의되어 있습니다.

  • 트리의 왼쪽 노드에 요소를 추가하는 데 도움이 되는 'insert_to_left' 메서드가 있습니다.

  • 트리의 오른쪽 노드에 요소를 추가하는 데 도움이 되는 'insert_to_right' 메서드가 있습니다.

  • 트리에서 너비 우선 탐색을 수행하는 데 도움이 되는 'bfs' 방법이 있습니다.

  • 특정 요소를 검색하는 데 도움이 되는 'search_elem'이라는 메서드가 정의되어 있습니다.

  • 바이너리 트리의 복사본을 만드는 데 도움이 되는 'copy_mirror' 메서드가 있습니다.

  • 인스턴스가 생성되어 '없음'으로 지정됩니다.

  • 수행해야 하는 작업에 대해 사용자 입력을 받습니다.

  • 사용자의 선택에 따라 작업이 수행됩니다.

  • 관련 출력이 콘솔에 표시됩니다.