Я пытаюсь реализовать связанную структуру для дерева с помощью python, это выдержка из моего кода.
class Node(object):
def __init__(self,value,father=None,children=[]):
self.value=value
self.father=father
self.children=children
def __str__(self):
return self.value
class Tree(object):
def __init__(self,root=None):
self.root=root
def insertNode(self,new_node,father_value):
father_node=self.find_node(father_value)
if not father_node:
return False
new_node.father=father_node
print("Node's information BEFORE adding child to father's list of children")
print(f"Father node (find) {father_node}")
print(f"Father node's children {[x.value for x in father_node.children]}")
print(f"New node's father {new_node.father}")
print(f"New node's children {[x.value for x in new_node.children]}")
father_node.children.append(new_node)
print("Node's information AFTER adding child to father's list of children")
print(f"Father node (find) {father_node}")
print(f"Father node's children {[x.value for x in father_node.children]}")
print(f"New node's father {new_node.father}")
print(f"New node's children {[x.value for x in new_node.children]}")
def find_node(self,value):
stack=[self.root]
while True:
if len(stack)==0:
return False
node=stack.pop()
if node.value==value:
return node
children=node.children
stack.extend(children)
n1=Node("A")
tree=Tree(n1)
tree.insertNode(Node("B"),"A")
n1=Node("A")
tree=Tree(n1)
tree.insertNode(Node("B"),"A")
ВЫХОД
Node's information BEFORE adding child to father's list of children
Father node (find) A Father node's children [] New node's father A New node's children [] Node's information AFTER adding child to father's list of children Father node (find) A Father node's children ['B'] New node's father A New node's children ['B']
Как видите, когда я добавляю новый вставленный узел в список дочерних элементов отца, он также вставляется в список дочерних элементов нового узла. Как это исправить?