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