python - 打印二叉树中所有可能的路径

标签 python algorithm binary-tree

我试图在二叉树中打印所有可能的路径。我能够打印所有根到叶的路径,但无法弄清楚如何添加叶到叶的路径。(我对根到叶使用预序遍历)。 所以,基本上:

如果我的树是

       6
     /    \
    4      0
   / \      \
  1   3      1

如果要打印所有路径的代码:

6,4,1
6,4,3
6,0,1
1,4,6,0,1
3,4,6,0,1 
1,4,3  
4,6,0  
4,6,0,1  
etc.

任何人都可以帮我解决这个二叉树吗? 非常感谢您的帮助,因为我是这个社会和 Python/Java 的新手。

谢谢

最佳答案

树的一个显着特性是对于节点 (x, y) 的每个组合,都存在从 xy 的唯一非重复路径。特别是,可以通过找到 xy 的第一个共同祖先 z 并采用路径 x -> z + z -> y.

因此找到所有路径的算法可能如下所示

for each pair of distinct nodes x, y in the tree:
    find all common ancestors of x and y
    let z be the lowest common acestor in the tree
    let p be the path from x to z
    append the path from z to y to p, excluding the duplicate z
    print p

这是一种面向对象的方法,它实现了完成上述任务所需的方法。

class Tree:
    def __init__(self, value, left=None, right=None):
        self.value = value
        self.left = left
        self.right = right
        self.parent = None

        if left is not None:
            left.parent = self

        if right is not None:
            right.parent = self

    def __iter__(self):
        """Return a left-to-right iterator on the tree"""
        if self.left:
            yield from iter(self.left)
        yield self
        if self.right:
            yield from iter(self.right)

    def __repr__(self):
        return str(self.value)

    def get_ancestors(self):
        """Return a list of all ancestors including itself"""
        ancestors = {self}
        parent = self.parent
        while parent:
            ancestors.add(parent)
            parent = parent.parent

        return ancestors

    def get_path_to_ancestor(self, ancestor):
        """
        Return the path from self to ancestor as a list
        output format: [self, ..., ancestor]
        """
        path = []
        parent = self
        try:
            while True:
                path.append(parent)
                if parent is ancestor:
                    break
                else:
                    parent = parent.parent
        except AttributeError:
            return None

        return path

    def get_path_to(self, other):
        """
        Return the path from self to other as a list
        output format: [self, ..., first common acestor, ..., other]
        """
        common_ancestors = self.get_ancestors() & other.get_ancestors()
        first_common_ancestor = {
            a for a in common_ancestors
            if a.left not in common_ancestors and a.right not in common_ancestors
        }.pop()

        return self.get_path_to_ancestor(first_common_ancestor)\
               + list(reversed(other.get_path_to_ancestor(first_common_ancestor)))[1:]

以下是它如何应用于您作为示例提供的树。

tree = Tree(
    6,
    Tree(4,
         Tree(1),
         Tree(3)),
    Tree(0,
         Tree(1)))

nodes = list(tree)

for i in range(len(nodes)):
    for j in range(i + 1, len(nodes)):
        print([t for t in nodes[i].get_path_to(nodes[j])])

这是打印的所有路径。

[1, 4]
[1, 4, 3]
[1, 4, 6]
[1, 4, 6, 0, 1]
[1, 4, 6, 0]
[4, 3]
[4, 6]
[4, 6, 0, 1]
[4, 6, 0]
[3, 4, 6]
[3, 4, 6, 0, 1]
[3, 4, 6, 0]
[6, 0, 1]
[6, 0]
[1, 0]

关于python - 打印二叉树中所有可能的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50425656/

相关文章:

algorithm - 如果我将二叉树存储在数组中,如何避免浪费空间?

python - 如何设置内边距和外边距

python - 如何修复ModuleNotFoundError : No module named 'pip._internal' with python source code installation

c - 红黑树——初始化

java - 在 Hadoop 中实现采样和数据挖掘算法

结合树和节点,值(value)不可访问

python - Django:在保存模型时检测一组字段的变化

python - 创建 Django 模型或更新(如果存在)

algorithm - matlab中的大数回文

c - 确定恰好具有 4 个节点的子树数量的最佳方法是什么?