2 回答
TA贡献1770条经验 获得超3个赞
将它们作为参数传递,默认 = None:
def convert(root, prev = None, head = None):
if root is None:
return
convert(root.left, prev=prev, head=head)
if head== None:
head = root
prev = root
else:
root.left = prev
prev.right = root
prev = root
convert(root.right, prev=prev, head=head)
TA贡献1805条经验 获得超10个赞
我认为你需要返回链表的头。
不管怎样,你可以包装你的函数来为这两个变量创建一个闭包:
def convert(root):
head = None
prev = None
def recur(cur):
nonlocal prev, head
if cur is None:
return
recur(cur.left)
if head is None:
head = cur
else:
cur.left = prev
prev.right = cur
prev = cur
recur(cur.right)
recur(root)
return head
添加回答
举报