今天刷leetcode,在python的引用和浅拷贝的问题上面纠结了半天,做二叉树的题时一直分不清什么时候用浅拷贝才能避免出问题。那么,我们先定义一下二叉树的节点,就直接用LeetCode给的定义吧:
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
赋值引用
我们先定义了一个头节点node1,其左子树为node2:
node1 = TreeNode(1)
node2 = TreeNode(2)
node1.left = node2
然后用一个test节点,来看下赋值引用后,修改test对node1的影响:
test = node1 # 赋值引用
print("node1=",node1.val,",left=",node1.left.val)
print("test=",test.val,",left=",test.left.val)
# 赋值引用后,修改test
test.val = 5
test.left = TreeNode(3)
print('*'*20)
print("node1=", node1.val,",left=",node1.left.val)
print("test=", test.val,",left=",test.left.val)
输出结果为:
node1= 1 ,left= 2
test= 1 ,left= 2
********************
node1= 5 ,left= 3
test= 5 ,left= 3
可以看到,赋值引用后,两者是共享引用的,修改其中一个,另一个也会一同被修改
浅拷贝
如果是浅拷贝,那么会出现什么结果?
test = copy.copy(node1) # 浅拷贝
print("node1=",node1.val,",left=",node1.left.val)
print("test=",test.val,",left=",test.left.val)
# 浅拷贝后,修改test
test.val = 5
test.left = TreeNode(3)
print('*'*20)
print("node1=", node1.val,",left=",node1.left.val)
print("test=", test.val,",left=",test.left.val)
输出结果为:
node1= 1 ,left= 2
test= 1 ,left= 2
********************
node1= 1 ,left= 2
test= 5 ,left= 3
可以看到,浅拷贝之后,两个节点的引用也拷贝了一份,因此对test的修改,并不会影响到node1