代码之家  ›  专栏  ›  技术社区  ›  Nicole Foster

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

  •  1
  • Nicole Foster  · 技术社区  · 6 年前
    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):
    

    1 回复  |  直到 6 年前
        1
  •  1
  •   Kevin    6 年前

    我将编写一个函数,遍历树中所有可能的路径。然后我迭代这些路径,选择那些加起来等于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]将以7击败[2,5,4,2,1]。如果这是你想要的,你可以改变最后一行 searchMax return max(candidates, key=sum)


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

    您可以编写一个函数,将一个列表排列成若干个数据块,这些数据相加,然后在从中返回之前调用该函数 搜索最大值 .

    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]]