简体   繁体   中英

Find all parent nodes of a node in a tree

I am creating a tree in python, and I had a method to find a path from the parent to the root node of the tree. That is as follows:

def get_sub_net(self, index):
    node = self.nodes[index]
    sub_net = []
    sub_net.append(node)
    while node.parent is not None:
        node = node.parent
        sub_net.append(node)
    return sub_net[::-1]

Now I am trying to allow for each node to have multiple parents, and I am running into trouble.

def sub_net(self, index):
    node = self.nodes[index]
    sub_net = []
    if node.parents == None:
        return sub_net
    else:
        sub_net += node.parents
        for i in node.parents:
            while i is not None:
                sub_net += i.parents
                node = i
                break
    return sub_net[::-1]

@Noreddine-Kessa pointed out that this would be a graph, and not a tree, which is correct. However, I also solved my own problem, the solution I used i

def recursive_sub_net(self, node):
    sub_net = []
    sub_net.append(node)

    if node.parents is not None:
        for i in node.parents:
            sub_net += self.recursive_sub_net(i)

    return sub_net

根据定义,树中的每个节点都有一个父节点(并且可以有许多祖先),如果需要使用节点网络(而不是树),则应该使用图。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM