Generating a binary tree from data in python

I wanted to know how to read values โ€‹โ€‹from a list into a binary tree. I have such a triangle:

         0
       1   2
     3   4   5
   6   7   8   9

i wrote a node class like this

class node:
    def __init__(self,data,left=None,right=None):
        self.data=data
        self.left=left
        self.right=right

basically what i want to do is something like this

node (0, node (1), node (2))

I want to make a recursive function that can handle much larger triangles. Can you somehow tell me what I should do?

edit: it is obvious that the binary tree is not a way to approach this problem. what I basically want to know is all different combinations from top to bottom. e.g. 0,1,3,6 0,2,5,8 etc.

+3
source share
2 answers

It sounds like homework, so I wonโ€™t write code, but here are some tips:

  • , , 0 1 2 3 4 5 6 7 8 9

  • ( , 3 4 5 6), parents, . , .

- , - node . , ( node 1 2 1 2 , ).

+1

:

a = 'aBCdef'

:

- a -
- B C
B C -
- d e
d e f
e f -

(, "" ):

class Node:
    def __init__(self,data,left=None,right=None):
        self.data=data
        self.left=left
        self.right=right

    def __unicode__(self):
        return '%s %s %s' % (
                self.left.data if self.left or '-', 
                self.data, 
                self.right.data if self.right or '-')


nodelist = [Node(c) for c in a]

i,y = 0,1

while True:
    for x in range(y):
        nodelist[i].left = nodelist[i-1] if x!=0 else None
        nodelist[i].right = nodelist[i+1] if x!=y-1 else None
        i+=1
    if i<len(a):
        y+=1
    else:
        break

for n in nodelist:
    print unicode(n)
0

Source: https://habr.com/ru/post/1728760/


All Articles