【发布时间】:2019-02-20 21:55:24
【问题描述】:
我已经看到这段代码迭代了一个类的某些成员(如果它们存在的话)。值得注意的是,在二叉树中,遍历子节点直到没有更多子节点。
二叉树定义为..
# 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]
我不确定他们是如何想出那条线来遍历左右节点的,我永远不会当场想出那条线……我该如何剖析这条线?
【问题讨论】:
标签: python generator breadth-first-search iterable