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 of them is the right of the other), and I want to separate them.
I duplicated overlapping nodes and created one list, but I am missing something. The code I use for this:
self.root = root = BNodeItem(values[0][0], 0)
q = list()
q.append(root)
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]
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)
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 usually get None):
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, 141.9 in line = 1 has children 201.3 and 100 in line = 2, but 70.4 has children 100 and 49.6 in line 2 (100 is common).
Any suggestions?
EDIT: Has an error in len () when creating nodes from list values (invalid lists). There still seems to be a mistake.
Seems to work
, @Arthur:
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