简体   繁体   中英

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 separate them.

I duplicated the overlapping nodes and created a single list, but I am missing something. The code I use to do that:

self.root = root = BNodeItem(values[0][0], 0)
q = list()
q.append(root)

# make single tree list
tree_list = list()
tree_list.append(values[0][0])
for i in xrange(1, len(values[0])):
    ll = [i for i in numpy.array(values)[:, i] if i is not None]
    # duplicate the values
    p = []
    for item in ll[1:-1]:
        p.append(item)
        p.append(item)
    new_ll = list()
    new_ll.append(ll[0])
    new_ll.extend(p)
    new_ll.append(ll[-1])
    tree_list.extend(new_ll)
# fix tree
for ind in xrange(len(tree_list)/2 - 1):
    eval_node = q.pop(0)
    eval_node.left = BNodeItem(tree_list[2*ind + 1], 0)
    eval_node.right = BNodeItem(tree_list[2*ind + 2], 0)
    q.append(eval_node.left)
    q.append(eval_node.right)

the "values" variable looks like this(where 0 I get None normally):

100   141.9068   201.3753   285.7651    405.5200    575.4603
0     70.4688    100        141.9068    201.3753    285.7651
0     0          49.6585    70.4688     100.0000    141.9068
0     0          0          34.9938     49.6585     70.4688
0     0          0          0           24.6597     34.9938
0     0          0          0           0           17.3774

So for example the 141.9 in row = 1 has children 201.3 and 100 in row = 2, but 70.4 has children 100 and 49.6 in row 2(100 is shared).

Any suggestions?

EDIT : Had an error in len() and in creating the nodes from list values(wrong lists). Seems to still have a bug.

Seems it's working

Use this to print the tree from @Arthur's solution:

class Node():
    def __init__(self, value):
        self.value = value

        self.leftChild = None
        self.rightChild= None
    def __str__(self, depth=0):
        ret = ""
        if self.leftChild is not None:
            ret += self.leftChild.__str__(depth + 1)
        ret += "\n" + ("                                     " * depth) + str(self.value)
        if self.rightChild is not None:
            ret += self.rightChild.__str__(depth + 1)
        return ret

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

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

def exceptFirstLine(data):
    if data :
        return data[1:]

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

def right(data):
    """ Returns the part of the data used to build the right subtree """
    return exceptFirstColumn(exceptFirstLine(data))
class Node():
    def __init__(self, value):
        self.value = value

        self.leftChild = None
        self.rightChild= None

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

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

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

        return node

    else :
        return None

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--+
|     |     |     |
3     5     5     6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM