简体   繁体   English

在 n 叉树的子节点数组中搜索节点

[英]Search a node in array of children nodes in n-ary tree

I'm stuck quith this issue from 2 weeks.我从 2 周起就被困在这个问题上。

I have a basic treenode class in Python:我在 Python 中有一个基本的 treenode 类:

class Node:
    def __init__(self, data):
        self.data= data
        self.children = []
        self.parent = None

then I have a generic recursive search function:然后我有一个通用的递归搜索功能:

def find_node(node, data):
    if node.data == data:
        return node

    if len(node.children)>0:
        for child in node.children:
            find_node(child, data)

I can't figure out why Python is searching only in the first occurrency of each "data" I pass to the find_node function.我不明白为什么 Python 只在我传递给 find_node 函数的每个“数据”的第一个 occurrency 中进行搜索。

I'm passing always the root node and then the string that identifies the node I'm looking for.我总是传递根节点,然后传递标识我正在寻找的节点的字符串。

Really banging my head on the wall.真的把我的头撞在墙上。

There are two problems in your code the first is that you are not returning the node if the function is called recursively.您的代码中有两个问题,第一个是如果递归调用该函数,您将不会返回节点。 The second is that if you if you just use return find_node(child, data) the function will return on first pass but you only want to return if a node was found within the recursion function.第二个是,如果您只使用return find_node(child, data)该函数将在第一次通过时返回,但您只想在递归函数中找到节点时返回。 Therefor you have to change因此你必须改变

find_node(child, data)

with something like

potNode = find_node(child, data)
if not potNode is None:
    return potNode

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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