我已经看过了这段代码,该代码通过类的某些成员(如果存在)进行迭代。值得注意的是,在二叉树中,遍历子项直到没有更多子项为止。
二叉树定义为..
# 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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句