|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +# 2583. Kth Largest Sum in a Binary Tree |
| 4 | +# Medium |
| 5 | +# https://leetcode.com/problems/kth-largest-sum-in-a-binary-tree |
| 6 | + |
| 7 | +=begin |
| 8 | +You are given the root of a binary tree and a positive integer k. |
| 9 | +The level sum in the tree is the sum of the values of the nodes that are on the same level. |
| 10 | +Return the kth largest level sum in the tree (not necessarily distinct). If there are fewer than k levels in the tree, return -1. |
| 11 | +Note that two nodes are on the same level if they have the same distance from the root. |
| 12 | +
|
| 13 | +Example 1: |
| 14 | +Input: root = [5,8,9,2,1,3,7,4,6], k = 2 |
| 15 | +Output: 13 |
| 16 | +Explanation: The level sums are the following: |
| 17 | +- Level 1: 5. |
| 18 | +- Level 2: 8 + 9 = 17. |
| 19 | +- Level 3: 2 + 1 + 3 + 7 = 13. |
| 20 | +- Level 4: 4 + 6 = 10. |
| 21 | +The 2nd largest level sum is 13. |
| 22 | +
|
| 23 | +Example 2: |
| 24 | +Input: root = [1,2,null,3], k = 1 |
| 25 | +Output: 3 |
| 26 | +Explanation: The largest level sum is 3. |
| 27 | +
|
| 28 | +Constraints: |
| 29 | +* The number of nodes in the tree is n. |
| 30 | +* 2 <= n <= 105 |
| 31 | +* 1 <= Node.val <= 106 |
| 32 | +* 1 <= k <= n |
| 33 | +=end |
| 34 | + |
| 35 | +# Definition for a binary tree node. |
| 36 | +# class TreeNode |
| 37 | +# attr_accessor :val, :left, :right |
| 38 | +# def initialize(val = 0, left = nil, right = nil) |
| 39 | +# @val = val |
| 40 | +# @left = left |
| 41 | +# @right = right |
| 42 | +# end |
| 43 | +# end |
| 44 | +# @param {TreeNode} root |
| 45 | +# @param {Integer} k |
| 46 | +# @return {Integer} |
| 47 | +def kth_largest_level_sum(root, k) |
| 48 | + return -1 if root.nil? |
| 49 | + |
| 50 | + sums = [] |
| 51 | + queue = [root] |
| 52 | + |
| 53 | + while !queue.empty? |
| 54 | + lvl_sum = 0 |
| 55 | + size = queue.size |
| 56 | + |
| 57 | + size.times do |
| 58 | + node = queue.shift |
| 59 | + lvl_sum += node.val |
| 60 | + |
| 61 | + queue << node.left if node.left |
| 62 | + queue << node.right if node.right |
| 63 | + end |
| 64 | + |
| 65 | + sums << lvl_sum |
| 66 | + end |
| 67 | + |
| 68 | + return -1 if k > sums.size |
| 69 | + |
| 70 | + sums.sort.reverse[k - 1] |
| 71 | +end |
0 commit comments