简体   繁体   English

这个具有两种不同返回类型的递归函数是如何工作的?

[英]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在哪里适合所有这些。

  1. How does returning two different types of objects ( boolean and List[str] ) work in this recursive function?在这个递归函数中如何返回两种不同类型的对象( booleanList[str] )?
  2. Why are we returning 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.

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