假设我有节点类:
class Node:
def __init__(self, data, link=None):
self.data = data
self.link = link
class BTNode:
def __init__(self, item, left=None, right=None):
self.item = item
self.left = left
self.right = right
我想创建一个二叉搜索树中序遍历的链表。
到目前为止,我所拥有的是:
def inorder(root):
root = _inorder(root)[0] # return head of linked list
# helper function that returns the head and tail of the linked list.
def _inorder(root):
if root is None:
return None, None
else:
temp = Node(root.item)
if root.left:
left_head, left_tail = _inorder(root.left)
left_tail.link = temp
if root.right:
right_head, right_tail = _inorder(root.right)
temp.link = right_head
return left_head, right_tail
测试:
if __name__ == '__main__':
a1 = BTNode('A')
a2 = BTNode('B')
a3 = BTNode('C')
a4 = BTNode('D')
a5 = BTNode('G')
a6 = BTNode('E')
a7 = BTNode('F')
a1.left = a2
a1.right = a3
a2.right = a4
a4.left = a5
a3.left = a6
a3.right = a7
x = inorder(a1)
但是我得到了错误:
UnboundLocalError:分配前引用的局部变量“left_head”
相反,如果我做类似的事情:
def _inorder(root):
if root is None:
return None, None
else:
temp = Node(root.item)
#if root.left:
left_head, left_tail = _inorder(root.left)
left_tail.link = temp
#if root.right:
right_head, right_tail = _inorder(root.right)
temp.link = right_head
return left_head, right_tail
然后错误变为: NoneType' object has no attribute 'link' 任何人都可以看到问题,因为我认为我的逻辑是正确的。