假设我有节点类:
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
我想创建二叉搜索树的inorder遍历的链表。
到目前为止我所拥有的是:
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'对象没有属性'link' 任何人都可以看到问题,因为我认为我的逻辑是对的。
答案 0 :(得分:0)
在第一种情况下:
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
如果你没有输入任何一个ifs,你将永远不会指定left_head或right_tail。
第二个错误是因为您第一次检查:
if root is None:
return None, None
给出了这项任务:
left_head, left_tail = _inorder(root.left)
将left_head和left_tail都设为None。这会导致您在下一行中看到爆炸。