【发布时间】:2017-08-23 13:29:57
【问题描述】:
我正在尝试使用链表对二叉树进行前序遍历。
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 -> 4 -> 5' 作为预购函数的输出。我不太清楚为什么。有人可以告诉我如何编辑我当前的代码来解决这个问题吗?
【问题讨论】:
标签: python-3.x recursion linked-list binary-tree