theguy
theguy

Reputation: 49

Tree in python not printing child elements

I have the following code and when I run it, I am not able to get the child elements printed:

class TreeNode:
    def __init__(self,data):
        self.data = data
        self.children = []
        self.parent = None

     #add child node
    def add_child(self,child):
        child.parent = self #the parent of the child is self
        self.children.append(child)

    def print_tree(self):
        print(self.data)
        if self.children:
            for child in self.children:
                child.print_tree()

def build_product_tree():
    root = TreeNode("Fruits") #will be stores in self.data of the treenode
                                  # fruits becomes the parent element

    apple = TreeNode("Apple") #apple becomes the child element now
    apple.add_child(TreeNode("green apple"))
    apple.add_child(TreeNode("red apple")) #these are children element of the apple node

    mango = TreeNode("Mango") #another child element of fruits
    mango.add_child(TreeNode("ripe mango"))
    mango.add_child(TreeNode("sweet mango"))

    #adding the apple and mango nodes as children to the root of the tree
    root.add_child(TreeNode("Apple"))
    root.add_child(TreeNode("Mango"))

    return root

if __name__ == '__main__':
    root = build_product_tree()
    root.print_tree()
    pass

From my understanding, fruits is the root of the tree and apple and mango get added in as children. However I would expect the children of apple and mango to be printed as well (green apple, red apple, etc) however they are not. Not quite sure why.

Upvotes: 0

Views: 31

Answers (1)

flakes
flakes

Reputation: 23624

Because you redeclared the children.

root.add_child(TreeNode("Apple"))
root.add_child(TreeNode("Mango"))

You want:

root.add_child(apple)
root.add_child(mango)

Note a debugger like PyCharm is very useful for identifying issues like this:

enter image description here

Upvotes: 2

Related Questions