[Tutor] How to create a binary tree hierarchy given a list of elements as its leaves

marc nicole mk1853387 at gmail.com
Sun Jan 28 18:11:47 EST 2024


Here's the tree example I attached earlier which shows how to go from leaf
nodes (0,1,2,3) to the root node (the range[0,3]) my problem (bug) in the
code is that the generated intermediate intervals for the nodes don't fit
each other because of the way I binary split the input array

C1[0,3]
├── B1[0,1]
│   ├── A0(0)
│   └── A1(1)
└── B2[2,3]
    ├── A2(2)
    └── A3(3)

Le dim. 28 janv. 2024 à 20:12, Alan Gauld via Tutor <tutor at python.org> a
écrit :

> On 28/01/2024 18:16, marc nicole via Python-list wrote:
> > So I am trying to build a binary tree hierarchy given numerical elements
> > serving for its leaves (last level of the tree to build). From the
> leaves I
> > want to randomly create a name for the higher level of the hierarchy and
> > assign it to the children elements. For example: if the elements inputted
> > are `0,1,2,3` then I would like to create firstly 4 elements (say by
> random
> > giving them a label composed of a letter and a number) then for the
> second
> > level (iteration) I assign each of 0,1 to a random name label (e.g. `b1`)
> > and `2,3` to another label (`b2`) then for the third level I assign a
> > parent label to each of `b1` and `b2` as `c1`.
> >
> > An illustation of the example is the following tree:
> >
> >
> > [image: tree_exp.PNG]
>
> Unfortunately the Python mail servers strip out binary
> attachments so we can't see the example.
>
> Which is a pity because I don't really understand your
> explanation, particularly about the random labelling
> of parents.
>
> Also you are using an ordered set of inputs which is usually
> a bad case for a binary tree - it turns into a linear list...
>
> However, I notice you've included several other mailing
> lists so maybe someone else will comprehend your intention.
>
> Meanwhile, for a basic Python binary tree implementation
> example you could try here:
>
> https://www.askpython.com/python/examples/binary-tree-implementation
>
> That may or may not help!
>
> I'm actually surprised it's not already in the standard
> library somewhere, but I couldn't find one.
>
> --
> 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
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>


More information about the Tutor mailing list