遍历树以收集所有子节点,排除不相关的分支
创始人
2024-12-04 06:30:14
0

在树的节点上添加一个属性来表示该节点的父节点,然后利用递归函数遍历整棵树,将所有节点和其关联的父节点储存在字典中。最后根据某个节点找到它的后代节点列表。

代码示例:

class Node: def init(self, value, parent=None): self.value = value self.parent = parent self.children = []

def add_child(self, node):
    self.children.append(node)
    node.parent = self

def traverse_tree(self):
    # dictionary to store nodes and their corresponding parents
    visited = {self: None}

    # recursive function to traverse tree
    def recursion(node):
        for child in node.children:
            visited[child] = node
            recursion(child)

    recursion(self)

    # get descendants of a node
    def get_descendants(node):
        descendants = []
        for child in node.children:
            if child in visited:
                descendants.append(child)
                descendants.extend(get_descendants(child))
        return descendants

    return visited, get_descendants

create a sample tree

root = Node(1) node2 = Node(2) node3 = Node(3) node4 = Node(4) node5 = Node(5) node6 = Node(6)

root.add_child(node2) root.add_child(node3) node2.add_child(node4) node2.add_child(node5) node4.add_child(node6)

traverse the tree and get descendants

visited, get_descendants = root.traverse_tree()

print all nodes and their corresponding parents

for node, parent in visited.items(): print(node.value, parent.value if parent else None)

get descendants of node 2

print([node.value for node in get_descendants(node2)]) # [4, 5, 6]

相关内容

热门资讯

推荐一款!闲来贵州麻将有挂吗(... 推荐一款!闲来贵州麻将有挂吗(透明挂)一直是真的有挂(2022已更新)(哔哩哔哩)1、下载好闲来贵州...
wepoke辅助有挂!wepo... wepoke辅助有挂!wepoke外 挂,wepoke系统是免费的,黑科技教程(有挂工具);wepo...
微扑克wpk透视辅助!德州wp... 1、微扑克wpk透视辅助!德州wpk德州有挂,微扑克辅助机器人,插件教程(有挂解说);代表性(透视辅...
实测交流!填大坑辅助器通用版(... 实测交流!填大坑辅助器通用版(辅助)真是存在有挂(2022已更新)(哔哩哔哩)1、填大坑辅助器通用版...
微扑克辅助机器人!微扑克这软件... 微扑克辅助机器人!微扑克这软件有问题,微扑克可以用模拟器,力荐教程(有挂普及)是一款可以让一直输的玩...
WePoKe透明挂!wepok... WePoKe透明挂!wepoke有科技,wepoke可以来好牌,必备教程(有挂方法)是一款可以让一直...
微扑克ai机器人!微扑克有挂,... 微扑克ai机器人!微扑克有挂,微扑克大厅机器人(本来存在有挂),亲,有的,ai轻松简单,又可以获得无...
AI教程!wepoke透明挂辅... AI教程!wepoke透明挂辅助(wepoke智能ai)德州wepower(都是真的有挂);建议优先...
微扑克系统发牌规律!微扑克发牌... 微扑克系统发牌规律!微扑克发牌有问题(透视辅助)一贯真的是有挂1、超多福利:超高返利,海量正版游戏,...
盘点一款!掌酷十三张辅助是真的... 盘点一款!掌酷十三张辅助是真的吗(辅助挂)竟然是真的有挂(2025已更新)(哔哩哔哩);一、掌酷十三...