Classes python doubt

i have a doubt regarding classes.Please look at the codebyte below. the program runs fine but when i keep child_node instead of child_node.value() in line 8 it throws an error. why?

# Define your "TreeNode" Python class below class TreeNode: def __init__(self, value): self.value = value self.children = [] def add_child(self, child_node): print("Adding " + child_node.value) self.children.append(child_node) root = TreeNode("I am Root") child = TreeNode("A wee sappling") bad_seed = TreeNode("Root Rot!") root.add_child(child) root.add_child(bad_seed)

In trees, nodes are objects. Children and parent nodes therefore are objects as well. Unlike arrays, there is no index that any given node can point to and say go there. Once you are at a given node, you only have access to: 1. that node, 2. its children, 3. its parents.

If instead of an object the children and parents were values, the following would happen. You start at node A, and you say one of the child’s value is 15. But then what about the value of the child’s child? You can’t manipulate the value 15 to give you that.

1 Like

Thanks for the detailed explanation. It didn’t occur to me that if the child and parent were values i couldn’t link or connect two nodes.

You can link them, just not by value :slight_smile: