leetcode-5.18[985. 查询后的偶数和、404. 左叶子之和](python实现)

题目1

在这里插入图片描述

题解1

class Solution:
    def sumEvenAfterQueries(self, A: List[int], queries: List[List[int]]) -> List[int]:
        S = sum(item for item in A if item%2==0)
        sum_even = []
        for item in queries:
            index = item[1]
            # 如果选到该元素,则先剔除
            if A[index]%2==0:
                S -= A[index]
            A[index] += item[0]
            # 如果改变后是偶数,则添加
            if A[index]%2==0:
                S += A[index]
            sum_even.append(S)
        return sum_even

附上题目链接

题目2

在这里插入图片描述

题解2

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

class Solution:
    def sumOfLeftLeaves(self, root: TreeNode) -> int:
        """
            递归
        """
        if root is None:
            return 0
        # 如果存在左叶子节点
        if root and root.left and not root.left.left and not root.left.right:
            return root.left.val + self.sumOfLeftLeaves(root.right)
        # 如果没有左叶子节点,左叶子节点存在于左右子树中
        return self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)

    def sumOfLeftLeaves(self, root: TreeNode) -> int:
        """
            迭代
        """
        if root is None:
            return 0
        stack = [root]
        num = 0
        while stack:
            node = stack.pop()
            if node and node.left and not node.left.left and not node.left.right:
                num += node.left.val
            if node.left:
                stack.append(node.left)
            if node.right:
                stack.append(node.right)
        return num

附上题目链接

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值