我有一个(重组)二叉树t = ((4,), (3, 5), (2, 4, 6), (1, 3, 5, 7)),其中晶格层索引为(0,1,2,3)即4具有索引0,而3、5具有索引1,依此类推。我需要一组边的端点坐标(连接树节点)。自然地,4连接到3和5;3连接到2和4;5连接到4和6。
我可以采取什么方法吗?
输出是元素(按任意顺序)(它们是成对的)

[(0,4),(1,3)], [(0,4),(1,5)],
[(1,3),(2,2)], [(1,3),(2,4)], [(1,5),(2,4)], [(1,5),(2,6)],
[(2,2),(3,1)], [(2,2),(3,3)], [(2,4),(3,3)], [(2,4),(3,5)], [(2,6),(3,5)], [(2,6),(3,7)]

这棵树能长。任何基本数据(列表、集合、元组、字典等)都可以。
我原以为把一棵树转换成矩阵的下对角线会使事情变得更简单,但现在想想可能有直接的方法。
下面是此重组树的进度示例:
python - 将树节点转换为边缘端点的坐标-LMLPHP
如果需要澄清,请告诉我。

最佳答案

如果所有相邻节点都被视为对:

t = ((4,), (3, 5), (2, 4, 6), (1, 3, 5, 7))

from itertools import tee
a, b = tee(t)
next(b)
for ind, (t1, t2) in enumerate(zip(a, b)):
    print([[(ind, i), (ind + 1, j)] for i in t1 for j in t2])

您必须对输出进行分组,但这应该更接近您的需要:
def pairs(t):
    a, b = tee(t)
    next(b)
    for ind, (t1, t2) in enumerate(zip(a, b)):
        it = iter(t2)
        nxt = next(it)
        for ele in t1:
            n = next(it)
            yield [(ind, ele), (ind + 1, nxt)]
            yield [(ind, ele), (ind + 1, n)]
            nxt = n


from pprint import pprint as pp
pp(list(pairs(t)),compact=1)

输出:
[[(0, 4), (1, 3)], [(0, 4), (1, 5)], [(1, 3), (2, 2)], [(1, 3), (2, 4)],
 [(1, 5), (2, 4)], [(1, 5), (2, 6)], [(2, 2), (3, 1)], [(2, 2), (3, 3)],
 [(2, 4), (3, 3)], [(2, 4), (3, 5)], [(2, 6), (3, 5)], [(2, 6), (3, 7)]]

07-24 09:52
查看更多