简体   繁体   English

从Python中的列表列表创建二叉树

[英]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): “值”变量看起来像这样(其中0,我通常None得到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 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). 因此,例如,第1行中的141.9拥有201.3的孩子,第2行中有100的孩子,但是第2行中70.4的孩子100和49.6的孩子(共享100)。

Any suggestions? 有什么建议么?

EDIT : Had an error in len() and in creating the nodes from list values(wrong lists). 编辑:在len()和从列表值(错误列表)创建节点时出错。 Seems to still have a bug. 似乎仍然有错误。

Seems it's working 似乎正在运作

Use this to print the tree from @Arthur's solution: 使用它来打印@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

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. 这里有一个解决方案,该解决方案返回一个具有左右孩子的Node对象,使您可以使用大多数树解析算法。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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