我已经看到这段代码迭代了类的某些成员(如果它们存在)。值得注意的是,在二叉树中,迭代孩子,直到没有更多的孩子。
二叉树定义为..
# 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
如果我没有弄错的话,这句话是一种创建列表的pythonic和short-hand方式。
# 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:
level_list.append(child)
理解这个简写语句的技巧是通过查看外围边界符号,在这种情况下,这些是[
和]
。它用python中的列表序列标识。由于列表中有迭代器(for
循环),我们基本上在上述列表中创建或添加元素(变量child
)。
/还