I want to re-construct a Tree From a dictionary. But Here I found that in the recursion, when I create a new Treenode (named node). The ID for node.next_nodes and its parent root.next_nodes are exactly the same. I wonder why this happens?
mydict = {'1': ['21', '22', '23', '24'],
'21': ['211'],
'22': ['221', '222'],
'24': ['241', '242', '243']}
class TreeNode():
def __init__(self, val = '0', next_nodes = []):
self.val = val
self.next_nodes = next_nodes
root = TreeNode('1')
def decode(root):
if root.val not in mydict:
return None
for node_val in mydict[root.val]:
node =TreeNode(node_val)
print(id(root.next_nodes), id(node.next_nodes))
root.next_nodes.append(node)
decode(node)
decode(root)