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

附上題目鏈接

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章