Let’s explore how to remove nodes from a tree. Remember, child nodes are held in a list within the parent node. To remove a child, we need to remove that node from the list.
We want the following functionality:
print(root.children) # [child_a, child_b, child_c] root.remove_child(child_b) print(root.children) # [child_a, child_c]
.remove_childon a specific node.
- Pass another node as an argument
- Remove from
.childrenany nodes which match the argument node.
Inside of the TreeNode class, define a new method
remove_child, which has parameters of
child_node. Print “Removing “ +
child_node.value + “ from “ +
In the body of
remove_child, make a local variable,
new_children, and set it to an empty list.
self.children and add to the
new_children list any item that is not the same as the
When the iteration is over, assign
self.children to be the
root and pass
bad_seed as an argument.