From f296aac12311a84e18c471ffd9bcb2537d787b5d Mon Sep 17 00:00:00 2001 From: chayan das <110921638+Chayandas07@users.noreply.github.com> Date: Tue, 22 Oct 2024 14:10:04 +0530 Subject: [PATCH] Create 2583. Kth Largest Sum in a Binary Tree --- 2583. Kth Largest Sum in a Binary Tree | 41 ++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 2583. Kth Largest Sum in a Binary Tree diff --git a/2583. Kth Largest Sum in a Binary Tree b/2583. Kth Largest Sum in a Binary Tree new file mode 100644 index 0000000..b0f5033 --- /dev/null +++ b/2583. Kth Largest Sum in a Binary Tree @@ -0,0 +1,41 @@ +/** + * 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) { + priority_queue, greater>pq; + if (root == NULL) + return 0; + + queue q; + q.push(root); + while (!q.empty()) { + int size = q.size(); + long long sum = 0; + for (int i = 0; i < size; i++) { + TreeNode* node = q.front(); + q.pop(); + if (node->left) + q.push(node->left); + if (node->right) + q.push(node->right); + sum += node->val; + } + pq.push(sum); + if(pq.size() > k) + pq.pop(); + } + if(pq.size() < k) + return -1; + return pq.top(); + } +};