Print all possible paths in binary tree

送分小仙女□ 提交于 2021-02-17 03:29:09

问题


I'm trying to print all possible paths in a binary tree. I am able to print all root to leaf paths, but cannot figure out how to add leaf-to-leaf paths.(i'm using preorder traversal for root to leaf). So, basically:

If my tree is

       6
     /    \
    4      0
   / \      \
  1   3      1

If want to the code to print all the paths:

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.

Can anyone please help me with this binary tree? I would really appreciate your help, as I'm new to this society and to Python/Java.

Thanks


回答1:


One notable property of trees is that for every combination of node (x, y), there exist a unique non-repeating path from x to y. In particular, this path can be found by finding the first common ancestor z of x and y and by taking the path x -> z + z -> y.

Thus an algorithm to find all path could look like this

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

Here is an object-oriented approach that implements the needed method to accomplish the above.

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

Here is how it applies to the tree you provided as example.

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

Here are all paths that get printed.

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


来源:https://stackoverflow.com/questions/50425656/print-all-possible-paths-in-binary-tree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!