【问题标题】:Ternary tree paths三元树路径
【发布时间】:2021-08-06 10:04:10
【问题描述】:

我正在解决以下问题:

给定一棵三叉树(树的每个节点最多有三个 children),找到所有从根到叶的路径。

示例:

我的代码如下:

from __future__ import annotations

import itertools
from collections import deque, Iterable


class TernaryNode:
    def __init__(self, val: int) -> None:
        self.children: list[TernaryNode] = []
        self.val = val

    def __repr__(self) -> str:
        return str(self.val)


def ternary_tree_paths(root: TernaryNode) -> Iterable[Iterable[int]]:
    def _visit(node: TernaryNode) -> Iterable[deque[int]]:
        if not node:
            return []
        if not node.children:
            queue = deque()
            queue.append(node.val)
            return [queue]
        # **
        paths = itertools.chain.from_iterable(map(lambda ch: _visit(ch), node.children))
        for p in paths:
            p.appendleft(node.val)

        return paths

    return _visit(root)

如图所示,上面的代码返回一个空列表,其中所需的行为是[deque([1, 2, 3]), deque([1, 4]), deque([1, 6])]。注意带**的行;如果我将该行重写为paths = [p for ch in node.children for p in _visit(ch)],它将按预期工作。我猜这个问题是因为函数 from_iterable 被延迟评估,但是当我迭代项目时不应该强制评估吗?

【问题讨论】:

  • 很高兴提供minimal reproducible example...
  • @Julien 你在看。
  • 您的代码中没有定义实际的树。上面的代码是否显示您的错误?不,它没有。所以它不是minimal reproducible example
  • 我只是说最好提供一个可以复制和粘贴的示例,而不是期望人们从图片中自己编写代码。你当然没有义务像那些仍然试图帮助你的人那样友善。祝你有美好的一天:)
  • 这能回答你的问题吗? Python: calling 'list' on a map object twice

标签: python algorithm data-structures functional-programming ternary-tree


【解决方案1】:

尝试对每个项目执行appendleft 时,您正在耗尽可迭代链。之后paths 为空。

您需要确保迭代只被评估一次:

def ternary_tree_paths(root: TernaryNode) -> Iterable[Iterable[int]]:
    def _visit(node: TernaryNode) -> Iterable[deque[int]]:
        if not node:
            return []
        if not node.children:
            queue = deque()
            queue.append(node.val)
            return [queue]
        paths = itertools.chain.from_iterable(map(_visit, node.children))
        retval = [] # to keep track of results
        for p in paths: # iterate
            p.appendleft(node.val)
            retval.append(p) # add to result

        return retval # return result

    return _visit(root)

这会产生:

[deque([1, 2, 3]), deque([1, 4]), deque([1, 6])]

对于问题中的示例。

【讨论】:

  • 谢谢。似乎使用列表解决了这个问题,而不需要额外的列表retval
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-18
  • 2016-08-16
  • 2022-01-21
相关资源
最近更新 更多