연결된 목록을 사용하여 이진 트리의 선행 순서 탐색을 시도하고 있습니다.연결된 목록을 사용하여 이진 트리 탐색
class BTNode:
"""A node in a binary tree."""
def __init__(self: 'BTNode', item: object,
left: 'BTNode' =None, right: 'BTNode' =None) -> None:
self.item, self.left, self.right = item, left, right
class LLNode:
"""A node in a linked list."""
def __init__(self: 'LLNode', item: object, link: 'LLNode' =None) -> None:
self.item, self.link = item, link
def __str__(self: 'LLNode') -> str:
"""Return an informative string showing self
>>> b = LLNode(1, LLNode(2, LLNode(3)))
>>> str(b)
'1 -> 2 -> 3'
"""
return str(self.item) + (' -> ' + str(self.link) if self.link else '')
def preorder(root: BTNode) -> LLNode:
"""Return the first node in a linked list that contains every value from the
binary tree rooted at root, listed according to an preorder traversal.
>>> b = BTNode(1, BTNode(2), BTNode(3))
>>> repr(preorder(b))
'LLNode(1, LLNode(2, LLNode(3)))'
>>> b2 = BTNode(4, BTNode(5))
>>> b3 = BTNode(7, b, b2)
>>> str(preorder(b3))
'7 -> 1 -> 2 -> 3 -> 4 -> 5'
"""
return _preorder(root)[0]
def _preorder(root: BTNode) -> (LLNode, LLNode):
"""Return the first and last nodes in a linked list that contains every
value from the binary tree rooted at root, listed according to an preorder
traversal.
"""
if not root:
return None, None
left_head, left_tail = _preorder(root.left)
right_head, right_tail = _preorder(root.right)
# change from right_tail = left_tail to right_tail = left_head
if not right_tail:
right_tail = left_head
if not left_head:
left_head = right_head
if left_tail:
left_tail.link = right_head
root_node = LLNode(root.item, left_head)
return root_node, right_tail
나는 항상 얻고 대신에 '7 - -> 1> 2' '7 -> 1 -> 2 -> 3 -> 5 -> 4'예약 주문 기능에서 내 출력으로. 왜 그런지 잘 모르겠습니다. 누군가이 문제를 해결하기 위해 현재 코드를 편집 할 수있는 방법을 알려주십시오.
디버깅 해 주셔서 감사합니다. 그러나 코드의 어느 부분이 제대로 연결되어 있지 않은지 확실하지 않습니다. 추가 조건을 추가하거나 현재 조건 중 하나를 편집해야합니까? 나는 정말로 혼란 스럽다. –
현재로서는 디버깅 기술을 찾아야합니다. 예를 들어 종이에 나무를 그립니다. 맨 왼쪽 하위 트리가 올바르게 링크 될 때까지 한 번에 하나의 명령문으로 호출을 수행하십시오. 그건 7 -> 1 -> 2입니다. 이제, 오른쪽 하위 트리를 통해 한 레벨 및 종이 추적을 백업하십시오. 3. 변수 값을 기록하고 코드가 실제로 작동하는 방법을 조사하고, ** 얻은 곳을 찾습니다 ** 없음 **, 그러나 노드에 링크 할 것으로 예상했습니다. **삼**. – Prune
오른쪽 꼬리가 있는지 확인하는 if 조건을 변경했습니다. 편집 된 버전을 확인하십시오. 이제 '7 -> 1 -> 2 -> 4 -> 5'가 나오지만 왜 3이 포함되지 않는지 확실하지 않습니다. –