[Tutor] double nodes being enter into tree structure

Alan Gauld alan.gauld at yahoo.co.uk
Fri Jun 28 04:48:38 EDT 2019


On 28/06/2019 07:10, mhysnm1964 at gmail.com wrote:
>
> Anyway, my issue is I am getting the same node being added to the parent node of my tree below. 

I'm not sure about that part but....

> def addNode(words, tree):
>     if words:
>         wordExists = False 
>         for child in tree.children:
>             if words[0] == child.name:
>                 wordExists = True
>         if not wordExists:
>             tree = tree.add(words[0], 0)
> 
>         addNode(words[1:], tree)

Notice that the recursive call is adding the subsequent
words to the same tree that was passed to addNode originally.
In other words you are not building a tee you are just
building a list of children under the top level tree node.

I suspect you want to add the subsequent words to the
children of the node you just added? Or the existing
one of the same value...

So you need something like(untested!)

        for child in tree.children:
             if words[0] == child.name
                nextNode = child
        else:
            nextNode = tree.addNode(words[0],0)

        addNode(words[1:], nextNode)


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list