gpt4 book ai didi

Python:复杂的迭代

转载 作者:行者123 更新时间:2023-12-01 01:36:25 25 4
gpt4 key购买 nike

我见过这段代码,它会迭代类的某些成员(如果存在)。值得注意的是,在二叉树中,迭代子节点直到没有更多的子节点。

二叉树定义为..

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

他们已经这样迭代了:

# type root : TreeNode
def iterateTree(self, root):
level_list = [root]

while level_list:

for item in level_list:
print(item.val)

# This iterable seems really complicated for me to understand how they came up with this
level_list = [child for node in level_list for child in (node.left, node.right) if child]

我不确定他们是如何想出那条线来迭代左右节点的,我不会当场想出这一点...我将如何剖析这条线?

最佳答案

阅读如下:

for node in level_list:
for child in (node.left, node.right):
if child:
child

关于Python:复杂的迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52359866/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com