Skip to content Skip to sidebar Skip to footer

Create Binary Tree From List Of Lists In Python

I need to create a binary tree from a list of lists. My problem is that some of the nodes overlap(in the sense that the left child of one is the right of the other) and I want to s

Solution 1:

Here comes a solution that return you a Node object having left and right child allowing you to use most of the tree parsing algorithms. If needed you can easily add reference to the parent node.

data2 = [[1,2,3],
         [0,4,5],
         [0,0,6]]

defexceptFirstColumn(data):
    if data and data[0] :
        return [ row[1:] for row in data ]
    else :
        return []

defexceptFirstLine(data):
    if data :
        return data[1:]

defleft(data):
    """ Returns the part of the data use to build the left subTree """return exceptFirstColumn(data)

defright(data):
    """ Returns the part of the data used to build the right subtree """return exceptFirstColumn(exceptFirstLine(data))
classNode():
    def__init__(self, value):
        self.value = value

        self.leftChild = None
        self.rightChild= Nonedef__repr__(self):
        if self.leftChild != Noneand self.rightChild != None :
            return"[{0} (L:{1} | R:{2}]".format(self.value, self.leftChild.__repr__(), self.rightChild.__repr__())
        else:
            return"[{0}]".format(self.value)

deffromData2Tree(data):    
    if data and data[0] :
        node = Node(data[0][0])

        node.leftChild = fromData2Tree(left(data))
        node.rightChild= fromData2Tree(right(data))

        return node

    else :
        returnNone

tree = fromData2Tree(data2)
print(tree)

This code give the following result :

[1 (L:[2 (L:[3] | R:[5]] | R:[4 (L:[5] | R:[6]]]

That is the requested following tree. Test it on your data, it works. Now try to understand how it works ;)

   +-----1-----+
   |           |
+--2--+     +--4--+
|     |     |     |
3556

Post a Comment for "Create Binary Tree From List Of Lists In Python"