【问题标题】:while statement with stack in Inorder Traversal中序遍历中带有堆栈的while语句
【发布时间】: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


【解决方案1】:

在堆栈的最后,stack = []。这是一个长度为 0 的列表,而不是一个无对象。您可以通过尝试None == [] 来验证这一点,这将是False

【讨论】:

    【解决方案2】:

    您可以通过运行 Python IDE 并创建一个空数组来检查这种情况。然后,使用空数组,运行条件​​检查:

    temp = []
    temp is None
    

    输出为假。

    这告诉我们空数组不被认为是None,这是有道理的,因为数组不是空类型。

    【讨论】:

      猜你喜欢
      • 2015-03-25
      • 2016-08-13
      • 1970-01-01
      • 2012-02-17
      • 1970-01-01
      • 2014-06-05
      • 2022-01-17
      • 2021-01-18
      • 1970-01-01
      相关资源
      最近更新 更多