0
$\begingroup$

Given the root of a binary tree, for instance below, I am running the following tests in Python:

     1
    / \
   2   5
  / \
 3   4

Test 1:

cur = root
root = None
print(root, cur)
None, node 1

Test 2:

cur = root
root.left = None
print(root.left, cur.left)
None, None

In both tests cur and root point to the same memory location. In test 1, why changing root to None did not modify cur? But in test 2 when I assign root.left to None, cur.left is also changed?

$\endgroup$
1
0
$\begingroup$

Variable cur and root points to the same object at the start. Think of it as assigning an object two names - root and cur.

In test1 you changed the object pointed to by root. This means that the name root has been assigned to a different object. However, cur remains to be the name of the object at the start. So now root and cur do not point to the same object.

In your test2 you did not change the object pointed by root, but you modified the object shared by both cur and root, through root so changes to this shared object will be reflected in both.

Try to read this for more info https://realpython.com/python-variables/

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.