【发布时间】:2019-10-21 22:23:40
【问题描述】:
当我想将所有节点保存到一个中序列表sorted_node_val 中时,我使用while 语句。
def closestKValues(self, root, target, k):
# write your code here
stack = []
sorted_node_val = []
node = root
while node:
stack.append(node)
node = node.left
while stack is not None:
node = stack.pop()
sorted_node_val.append(node.val)
if node.right:
node = node.right
while node:
stack.append(node)
node = node.left
但是上面的代码会产生while stack is not None: 的错误,结果是
File "/Users/Python/901.py", line 35, in closestKValues
node = stack.pop()
IndexError: pop from empty list
我将 while 语句更改为 while stack: 并修复了此错误。
但是我想知道while stack is not None:和while stack:有什么区别
【问题讨论】:
-
stack = []==>stack is not None,这意味着您的程序进入循环并尝试从stack数组中弹出一个项目,即使它是空的(从顺便说一句)。 -
换句话说,
stack的值不会在你弹出最后一个元素后变为None。
标签: python while-loop stack tree-traversal