您的递归方法可能如下所示
FUNCTION exists(Node target, Node root):
Node[] children = root.getChildren()
IF children NOT null: //if there are children go on to visit each one
FOR child IN children:
IF exists(target,child):
RETURN true
ELSE: //the base case, when 'root' has no children check if it's the value
RETURN root.value == target
RETURN false //will only be reached from the first call to exists() if there hasn't been a match already
在 Python 中,这看起来像:
def exists(target,root):
if isinstance(root,list):
for child in root:
if exists(target,child):
return True
else:
return target == root
return False
一些例子:
print exists(2,[[[2]]])
print exists(2,[[1,4,5,[2]]])
print exists(2,[0,0,0,[0,[1,1,1]]])
>>>
True
True
False
python 中的迭代将是
def existsNR(value,root):
visitstack = [child for child in root]
while visitstack:
node = visitstack.pop()
if isinstance(node,list):
visitstack += node
else:
if node == value:
return True
return False
这背后的逻辑是,您遍历“root”的每个初始子代,对于每个有子代的子代,然后将子代推入堆栈并删除这些子代(子代)的“父代”。检查这些是否有孩子并以类似的方式添加它们......直到你到达一个没有孩子的地方,此时你检查是否相等。