如果我在二叉树上尝试以下代码片段,并尝试稍后打印arr和字符串,则arr会给出正确的结果但字符串为空。有什么想法吗?它是通过引用传递的列表和通过值传递的字符串吗?
def post_order(root, arr = []):
if(root is not None):
post_order(root.left, arr)
post_order(root.right, arr)
arr.append(root.value)
def post_order1(root, string = ''):
if(root is not None):
post_order1(root.left, string)
post_order1(root.right, string)
string += str(root.value)
# assume I've made my binary tree
arr, string = [], ''
post_order(root, arr)
post_order1(root, string)
print arr, string
# arr holds the correct post-order sequence
# string is empty
答案 0 :(得分:2)
在Python中,列表是可变的,字符串是不可变的。这意味着可以修改列表,但字符串不能修改。字符串只能重新分配。
在您的函数中,您正在使用.append()
修改列表,但您只是重新分配字符串+=
答案 1 :(得分:1)
Arr是一个数组,你可以扩展它。传递给post_order1的字符串是一个不可变对象,更新时会创建一个副本。结果,原始字符串保持不变。
答案 2 :(得分:-1)
您应该像这样纠正您的代码:
def post_order1(root, string = ''):
if not root : return string
left = post_order1(root.left, string)
right = post_order1(root.right, left)
return right + str(root.value)