2583. Kth Largest Sum in a Binary Tree
You are given the root of a binary tree and a positive integer k.
The level sum in the tree is the sum of the values of the nodes that are on the same level.
Return the kth largest level sum in the tree (not necessarily distinct). If there are fewer than k levels in the tree, return -1.
Note that two nodes are on the same level if they have the same distance from the root.
Example 1:

Input: root = [5,8,9,2,1,3,7,4,6], k = 2 Output: 13 Explanation: The level sums are the following: - Level 1: 5. - Level 2: 8 + 9 = 17. - Level 3: 2 + 1 + 3 + 7 = 13. - Level 4: 4 + 6 = 10. The 2nd largest level sum is 13.
Example 2:

Input: root = [1,2,null,3], k = 1 Output: 3 Explanation: The largest level sum is 3.
Constraints:
- The number of nodes in the tree is
n. 2 <= n <= 1051 <= Node.val <= 1061 <= k <= n
C++
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: long long kthLargestLevelSum(TreeNode* root, int k) { vector<long long> arr; queue<TreeNode*> q{ {root} }; while (!q.empty()) { long long t = 0; for (int n = q.size(); n; --n) { root = q.front(); q.pop(); t += root->val; if (root->left) { q.push(root->left); } if (root->right) { q.push(root->right); } } arr.push_back(t); } if (arr.size() < k) { return -1; } sort(arr.rbegin(), arr.rend()); return arr[k - 1]; } };
PYTHON
from collections import deque 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: TreeNode, k: int) -> int: arr = [] q = deque([root]) while q: level_sum = 0 for _ in range(len(q)): node = q.popleft() level_sum += node.val if node.left: q.append(node.left) if node.right: q.append(node.right) arr.append(level_sum) if len(arr) < k: return -1 arr.sort(reverse=True) return arr[k - 1]
JAVA
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public long kthLargestLevelSum(TreeNode root, int k) { List<Long> arr = new ArrayList<>(); Deque<TreeNode> q = new ArrayDeque<>(); q.offer(root); while (!q.isEmpty()) { long t = 0; for (int n = q.size(); n > 0; --n) { root = q.pollFirst(); t += root.val; if (root.left != null) { q.offer(root.left); } if (root.right != null) { q.offer(root.right); } } arr.add(t); } if (arr.size() < k) { return -1; } Collections.sort(arr, Collections.reverseOrder()); return arr.get(k - 1); } }
Comments
Post a Comment