I created a small function funct
which should assign None
to node if a value of -1 is passed else assign the value to the value attribute of the node object. I created a simple binary tree [root, left, right] and finally print the nodes.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def funct(node, val):
if val == -1:
### modify code here
node = None
else:
node.val = val
root = TreeNode()
root.val = 'root'
root.left = TreeNode()
root.right = TreeNode()
funct(root.left, 'left')
funct(root.left, -1)
print(root, root.val)
print(root.left, root.left.val)
print(root.right, root.right.val)
When I print the nodes I see the following output.
The right node is in memory and is not None
.
How do I assign None
to the orignal object by modifying the code inside the if
in funct
to get the following output instead.
esentially simulating the following code and getting the output :
root = TreeNode()
root.val = 'root'
root.left = TreeNode('left')
root.right = None
Note : I can change my algo. to create a new node only when val != -1. However I want to understand if there is a way to modify a passed object it in pyhton.
Edits : removed the word "delete". Added some clarification.