[英]How does this recursive function with two different return types work?
This function below finds the instructions to get to a specified node in a binary tree ("L"= left, "R"= right).下面的这个函数找到了到达二叉树中指定节点的指令(“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
I see that the base case returns True
to finish the loop and also to tell preceding recursive calls that the path they're on will eventually reach the val node, but I don't understand where return path
fits into all of this.我看到基本情况返回
True
以完成循环,并告诉前面的递归调用它们所在的路径最终将到达 val 节点,但我不明白return path
在哪里适合所有这些。
boolean
and List[str]
) work in this recursive function?boolean
和List[str]
)?path
at all?path
呢? Removing that line does give me the wrong answer, but I don't see anywhere where the return value is set to a variable to be used somehow.A1. A1。 The "-> bool" is called Python type hint.
“-> bool”称为 Python 类型提示。 Python type hints are not used at runtime.
Python 类型提示在运行时不使用。
In fact, by the time your program runs, all the type information you've provided has been erased. In another word, Python doesn't care type.事实上,当您的程序运行时,您提供的所有类型信息都已被删除。
换句话说,Python 不关心类型。 You can learn more about Python type hint from here .
您可以从此处了解有关 Python 类型提示的更多信息。
A2-1. A2-1。 The
path
variable holds the search path. path
变量保存搜索路径。 When the path
in the top level find
is returned, you will get the full search path.当顶层
find
中的path
返回时,您将获得完整的搜索路径。
A2-2 The function in Python will returns None
if no return
in it. A2-2 如果没有
return
,Python 中的函数将返回None
。 For example:例如:
def foo():
print("hello")
the foo returns None
, same as foo2 below foo 返回
None
,与下面的 foo2 相同
def foo2():
print("hello")
return None
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.