herrDeng網內搜尋

自訂搜尋

Ads

2024年10月22日 星期二

C++ Python DFS與nth element( nlargest)Leetcode 2583 Kth Largest Sum in a...


Python C++ DFS與nth element nlargest解Leetcode 2583  Kth Largest Sum in a Binary Tree
用容器一次就配置大一點,寧可大一點不要不夠,解答的Code才會夠快。 解答快速程式簡單。
[Python解答請進]
----------
Python C++ DFS and nth_element( nlargest )solution Leetcode 2583 Kth Largest Sum in a Binary Tree
Once the container is used, the allocatioin should be larger. It is better to be larger than not enough, so that the code can be answered quickly enough. The answer is quick and simple.

# 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 kthLargestLevelSum(self, root: Optional[TreeNode], k: int) -> int:
        sum=[0]*100000
        sz=0
        def dfs(root, level):
            nonlocal sz
            if not root: return
            if sz<=level: sz+=1
            sum[level]+=root.val
            if root.left: dfs(root.left, level+1)
            if root.right: dfs(root.right, level+1)
        dfs(root, 0)
        if sz<k: return -1
        return heapq.nlargest(k, sum[:sz])[-1]
        

沒有留言:

Related Posts Plugin for WordPress, Blogger...

熱門文章