2 回答

TA貢獻(xiàn)1770條經(jīng)驗(yàn) 獲得超3個(gè)贊
將它們作為參數(shù)傳遞,默認(rèn) = 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貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超10個(gè)贊
我認(rèn)為你需要返回鏈表的頭。
不管怎樣,你可以包裝你的函數(shù)來為這兩個(gè)變量創(chuàng)建一個(gè)閉包:
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
添加回答
舉報(bào)