[英]How does this recursive function with two different return types work?
下面的这个函数找到了到达二叉树中指定节点的指令(“L”=左,“R”=右)。
def find(n: TreeNode, val: int, path: List[str]) -> bool:
if n.val == val:
return True
if n.left and find(n.left, val, path):
path += "L"
elif n.right and find(n.right, val, path):
path += "R"
return path
我看到基本情况返回True
以完成循环,并告诉前面的递归调用它们所在的路径最终将到达 val 节点,但我不明白return path
在哪里适合所有这些。
boolean
和List[str]
)?path
呢? 删除该行确实给了我错误的答案,但是我看不到任何将返回值设置为以某种方式使用的变量的地方。 A1。 “-> bool”称为 Python 类型提示。 Python 类型提示在运行时不使用。 事实上,当您的程序运行时,您提供的所有类型信息都已被删除。 换句话说,Python 不关心类型。 您可以从此处了解有关 Python 类型提示的更多信息。
A2-1。 path
变量保存搜索路径。 当顶层find
中的path
返回时,您将获得完整的搜索路径。
A2-2 如果没有return
,Python 中的函数将返回None
。 例如:
def foo():
print("hello")
foo 返回None
,与下面的 foo2 相同
def foo2():
print("hello")
return None
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.