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.
[codes on Leetcode]https://leetcode.com/problems/kth-largest-sum-in-a-binary-tree/solutions/5949574/dfs-nth-element-vs-bfs-min-heap-15ms-beats-99-02
Tree/ Graph play list]https://www.youtube.com/watch?v=bna7aw7dkPY&list=PLYRlUBnWnd5Kt0-3un43cwY6yT_il8NW
[動態規劃, dynamic programming, DP playlist]https://www.youtube.com/watch?v=30yq3fmE6E8&list=PLYRlUBnWnd5K_XYUesV9oc6M9ONXII61T
# 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]
沒有留言:
張貼留言
HTML 編輯器