English 中文(简体)
理解二进制树遍历中的递归
原标题:Understanding recursion in binary tree traversal

我正在尝试了解此代码是如何工作的:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

class Solution:
    def inorderTraversal(self, root: Optional[TreeNode], result: List[int] = None) -> List[int]:
        if result is None:
            result = []
        if root:
            self.inorderTraversal(root.left, result)
            result.append(root.val)
            self.inorderTraversal(root.right, result)
        return result

假设我们的树是[5,8,7](即,5是根,它的左子树是8,它的右子树是7)。首先,给出根作为输入。将创建空的结果列表。根不是None,因此执行if语句的主体。if语句的第一行应该调用根的左子项上的遍历函数,即root.left上的遍历。因此,我们回到“if result is None”这一行。跳过此first-if语句。对于第二个if语句,root.left为true,因此执行第二个if语句正文中的语句。也就是说,函数第二次调用自己,这次是在参数root.left.left上。所以我们回到“if result is None”这一行。再次跳过此first-if语句。现在我们转到“if-root.left.left”行。但是root.left.left是None,所以我们不应该执行语句体中的代码,我们应该返回“result”。我的错在哪里?

问题回答

函数interderTraversal采用两个参数:

  • <code>root</code>:表示当前节点。

  • <code>result</code>:一个包含遍历结果的列表。

当函数被调用时,它首先检查<code>根root不是None,则函数将继续遍历。它为左子树(root.left)启动对interderTraversal的递归调用,遍历它并将其值添加到结果列表中。随后,该函数将当前节点的值(root.val)附加到结果列表中,以确保值的正确顺序。然后,进行另一个递归调用,这次是对右子树(root.right),进一步扩展了结果名单。随着这些递归调用的展开,函数会逐步组装结果列表,以所需的顺序生成二进制树的值。如果<code>的结果为None</code>:check,则关注的问题与从新根开始遍历时初始化新的<code>结果





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签