IndexError: , How can I check if the last element in the list is null in this scenario without defining a method?

IndexError: , How can I check if the last element in the list is null in this scenario without defining a method?

这是一个 leet 代码问题,因此没有定义树。但这里是 TreeNode class 定义:(不适用于我的问题,但无论如何它在这里):

Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
    self.val = val
    self.left = left
    self.right = right

所以,这就是我所做的,但失败了,因为列表为空时无法访问。问题出现在### 指示的行上。

class Solution:
def postorderTraversal(self, root: TreeNode) -> List[int]:
    stack=[]
    output=[]
    node = root
    while True:
        if node:
            if (node.right != None):
                stack.append(node.right)
            stack.append(node)
            node=node.left
        elif stack:
            check=stack.pop()
            if (check.right != None) & (check.right == stack[-1]):     ###
                node=stack.pop()
                stack.append(check)
            else:
                output.append(check.val)
                node=None
        else:
            break
    return output

错误:

IndexError: list index out of range
if (check.right != None) & (check.right == stack[-1]):
Line 27 in postorderTraversal (Solution.py)
ret = Solution().postorderTraversal(param_1)
Line 57 in _driver (Solution.py)
_driver()
Line 68 in <module> (Solution.py)

因此,我添加了一个方法来执行堆栈[-1] 的检查以避免超出范围错误,在# 指示的行上。

def check_stack(stack):
if stack:
    return stack[-1]
else:
    return None

class Solution:
def postorderTraversal(self, root: TreeNode) -> List[int]:
    stack=[]
    output=[]
    node = root
    while True:
        if node:
            if (node.right != None):
                stack.append(node.right)
            stack.append(node)
            node=node.left
        elif stack:
            check=stack.pop()
            if (check.right != None) & (check.right == check_stack(stack)): #
                node=stack.pop()
                stack.append(check)
            else:
                output.append(check.val)
                node=None
        else:
            break
    return output

在这种情况下,是否有更简单的方法(无需创建新方法和更少的代码行)来执行堆栈[-1] 检查而不影响其他条件语句的顺序?

您可以通过使用切片获取堆栈的最后一个元素而不是访问特定索引来避免 check_stack 函数。

在这种情况下,如果堆栈中没有元素,您将得到空列表而不是 None

例如:

stack = [1,2]
stack[-1:] # 2

stack = []
stack[-1:] # []