【问题标题】:Path to each Leaf of a Binary Tree二叉树每个叶子的路径
【发布时间】:2022-01-26 01:26:49
【问题描述】:

AllPaths() 上面的函数将包含二叉树每个叶子的路径的数组附加到全局数组 res

代码工作得很好,但我想删除全局变量 res 并让函数返回一个数组。我该怎么做?

class Node:
    def __init__(self, value, left=None, right=None) -> None:
        self.value = value
        self.left  = left
        self.right = right

res = []
def allPaths(node, arr=[]):
    if node:
        tmp = [*arr, node.value]
        if not node.left and not node.right: # Leaf
            res.append(tmp)
        allPaths(node.left, tmp)
        allPaths(node.right, tmp)


root             = Node(1)
root.left        = Node(2);
root.left.left   = Node(4);
root.left.right  = Node(5);
root.right       = Node(3);
root.right.right = Node(6);
"""
          1         <-- root
        /   \
       2     3  
     /   \    \
    4     5    6    <-- leaves
"""
allPaths(root)
print(res)
# Output : [[1, 2, 4], [1, 2, 5], [1, 3, 6]]

【问题讨论】:

  • 请注意,您可以直接使用 root = Node(1, Node(2, Node(4), Node(5)), Node(3, None, Node(6))) 构建树

标签: python algorithm tree binary-tree


【解决方案1】:

让您完全避免内部列表和全局列表的一种简单方法是创建一个生成器,该生成器在它们到来时产生值。然后您可以将其传递给list 以得出最终结果:

class Node:
    def __init__(self, value, left=None, right=None) -> None:
        self.value = value
        self.left  = left
        self.right = right

def allPaths(node):  
    if node:
        if not node.left and not node.right: # Leaf
            yield [node.value]
        else:
            yield from ([node.value] + arr for arr in allPaths(node.left))
            yield from ([node.value] + arr for arr in allPaths(node.right))
              
root             = Node(1)
root.left        = Node(2);
root.left.left   = Node(4);
root.left.right  = Node(5);
root.right       = Node(3);
root.right.right = Node(6);
        
g = allPaths(root)
list(g)

# [[1, 2, 4], [1, 2, 5], [1, 3, 6]]

【讨论】:

    【解决方案2】:

    一种方法是回溯:

    def allPaths(node, partial_res, res):
        if not node: 
            return
        if not node.left and not node.right:
            res.append(partial_res[:] + [node.value])
            return    
        partial_res.append(node.value)
        allPaths(node.left, partial_res, res)
        allPaths(node.right, partial_res, res)
        partial_res.pop()
    
    res = []
    allPaths(root, [], res)
    print(res)
    

    【讨论】:

    • 怎么去掉全局变量res?
    • 函数所需的一切都是它的参数的一部分。您可以将其包装在另一个函数中,将其放入类中,甚至在最后返回结果。该函数不会改变任何未显式传递给它的变量。换句话说,虽然res 在这段代码中是全局的,但它不需要是全局的。我在这里没有这样做以将注意力集中在函数本身上。
    • 同意,但是你根本不回答这个问题
    【解决方案3】:

    我提供另一种选择。

    def allPaths(root, path=[]):
        tmp = []
        if root.left:
            tmp.extend(allPaths(root.left, path + [root.value]))
        if root.right:
            tmp.extend(allPaths(root.right, path + [root.value]))
        if not root.left and not root.right:
            tmp.append(path + [root.value])
        return tmp
    
    
    tree = allPaths(root)
    print(tree)
    

    输出是:

    [[1, 2, 4], [1, 2, 5], [1, 3, 6]]
    

    【讨论】:

      【解决方案4】:

      你可以在递归中传递当前路径:

      def allPaths(node,path=[]):
          if not node: return            # no node, do nothing
          fullPath = path + [node.value]
          if node.left or node.right:    # node is not a leaf, recurse down      
              yield from allPaths(node.left, fullPath)    # left leaves if any
              yield from allPaths(node.right, fullPath)   # right leaves if any
          else:
              yield fullPath             # leaf node, return final path
      

      【讨论】:

        猜你喜欢
        • 2021-02-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-11
        • 2016-08-29
        • 2018-11-26
        相关资源
        最近更新 更多