[Tutor] tree or link-list questions.

Alan Gauld alan.gauld at yahoo.co.uk
Tue Jun 25 12:48:03 EDT 2019


On 25/06/2019 13:24, mhysnm1964 at gmail.com wrote:
... the tree I am trying to create is:
> 
> *	A single root node
> *	A node can only have a single parent.
> *	A parent can have multiple children.
> *	Each node is unique.

A tree with multiple children (where multiple is more than 2)
is entirely possible but does make the code more complex.

Have you considered a binary tree where items go either left or right
depending on whether they are "greater than" or "less than" (for some
arbitrary definition of greater and less) than the parent node?
This is much simpler to code, and you will find lots of examples
online.

------ monospace font needed -------
<pre>
Root
   the
      brown
         fox
         cow
         car
      yellow
         car
      green
         house
      quick
         brown
            fox
   yellow
      flowers
</pre>
------ end of monospace font -------

The immediate questions you must answer (because only
you understand the requirements) are:
1) How do you know which tree branch to navigate down?
For example you have two car nodes. If searching for car
which is the correct answer? Similarly for fox?

2) How do you know to go down an extra level. For example
there are 4 nodes below 'the' What determines whether a
new node sits alongside the existing nodes or at a level
below.

3) Having decided you need to go a level lower how do
you know which subnode to go down? How do you insert the
node car into the correct subnode of the?(either brown
or yellow)

It looks like you are doing this based on the textual context.
That means you insertion code has to be stateful since
it must remember the previous word inserted (or have access
to the original data). That gets complicated really quickly.

Similarly, when you try to retrieve the data how do yu know which node
to fetch. For example if I search for fox? Surely you will need to
provide the full 'path' to fox topick the right one? But if you know the
path why search a tree?

In that case nested dictionaries would seem a better solution?
Something like(missing all the quotes!):

data = {
   the: [
      {brown: [
         {fox:[]},
         {cow:[]},
         {car:[]},
         ]},
      {yellow: [
         {car: []}
         ]},
      {green: [
         {house: []}
         ]},
      {quick: [
         {brown: [
             {fox: []}
             ]},
         ]},
       ]},
   {yellow: [
      {flowers: []}
      ]}
   ]}

Then you can access the appropriate path:

myFox = data[the][quick][brown][fox]

Just a thought. Since I don't really know how you intend
to use this I'm not sure if that would work for you.


-- 
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