如何使用ADT搜索python中的二叉树节点以获得最长树

2024-04-29 17:00:59 发布

您现在位置:Python中文网/ 问答频道 /正文

T = [[[[], [3, []]], [5, [[[[], [6, []]], [2, [[], [1, []]]]], [4, [[], [3, [[], [7, []]]]]]]]], [2, [[], [8, []]]]]

是二叉树的表示。你知道吗

以上T的代码很长,滚动查看完整代码

我在寻找最长的树,它的节点和是给定数的倍数。你知道吗

示例7上面的树T作为searchMax(T, 7)[[2,5], [4,3], [7]]返回,因为它是最长的,而且它的和是7的倍数

Pictorial representation

我定义了以下代码

def cons(x, y):
    return [x, y]

def car(p):
    return p[0]

def cdr(p):
    return p[1]

nil = []

def makeBinTree(root, left, right):
    return cons(left, cons(root, right))

emptyTree = nil


def isEmpty(tree):
    if len(tree) < 1:
        return True
    else:
        return False

def root(tree):
    return tree[1][0]

def left(tree):
    return tree[0][1]

def right(tree):
    return [1][1]

def searchMax(tree, number):

但我不知道从那以后该怎么办。你能帮我做这个吗。你知道吗


Tags: 代码righttree示例return节点defroot
1条回答
网友
1楼 · 发布于 2024-04-29 17:00:59

我将编写一个函数,遍历树中所有可能的路径。然后我迭代这些路径,选择那些加起来等于7的倍数的路径,然后从这些路径中选择最长的路径。你知道吗

def isEmpty(tree):
    if len(tree) < 1:
        return True
    else:
        return False

def root(tree):
    return tree[1][0]

def left(tree):
    return tree[0]

def right(tree):
    return tree[1][1]

def iter_all_paths(t):
    if isEmpty(t):
        return
    yield [root(t)]
    for child in (left(t), right(t)):
        for path in iter_all_paths(child):
            yield [root(t)] + path

def searchMax(t, x):
    #find all paths that add up to a multiple of x
    candidates = []
    for path in iter_all_paths(t):
        if sum(path) % x == 0:
            candidates.append(path)
    if not candidates: 
        return None
    return max(candidates, key=len)

T = [[[[], [3, []]], [5, [[[[], [6, []]], [2, [[], [1, []]]]], [4, [[], [3, [[], [7, []]]]]]]]], [2, [[], [8, []]]]]
print(searchMax(T, 7))

结果:

[2, 5, 4, 2, 1]

这与预期结果不同,[2,5,4,3,7]。这两个解的长度相同,所以我假设可以返回其中一个。我的解决方案返回最左边的路径,如果有一个领带长度。你知道吗


也许你在想“实际上我不想要最长的路径长度,而是要最大的节点总数”。然后[2,5,4,3,7]将以7击败[2,5,4,2,1]。如果这是您想要的,您可以将searchMax的最后一行更改为return max(candidates, key=sum)。你知道吗


您可能还会想“我更希望结果是一个列表列表,而不是一个int列表。我希望每个子列表加起来是数字的倍数。我想要的不是[2, 5, 4, 3, 7],而是[[2, 5], [4, 3], [7]]。你知道吗

您可以编写一个函数,将一个列表排列成与数字相加的块,并在从searchMax返回之前调用该函数。你知道吗

def chunk(seq, x):
    result = [[]]
    for item in seq:
        result[-1].append(item)
        if sum(result[-1]) % x == 0:
            result.append([])
    if not result[-1]:
        del result[-1]
    return result

#later, in searchMax...
    return chunk(max(candidates, key=len), x)

结果:

[[2, 5], [4, 2, 1]]

相关问题 更多 >