2583. Kth Largest Sum in a Binary Tree #735
-
Topics: You are given the The level sum in the tree is the sum of the values of the nodes that are on the same level. Return the Note that two nodes are on the same level if they have the same distance from the root. Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We'll follow these steps:
Let's implement this solution in PHP: 2583. Kth Largest Sum in a Binary Tree <?php
// Definition for a binary tree node.
class TreeNode {
public $val;
public $left;
public $right;
public function __construct($val = 0, $left = null, $right = null) {
$this->val = $val;
$this->left = $left;
$this->right = $right;
}
}
/**
* @param TreeNode $root
* @param Integer $k
* @return Integer
*/
function kthLargestLevelSum($root, $k) {
if ($root === null) {
return -1;
}
// Use BFS to traverse the tree level by level
$queue = [];
array_push($queue, $root);
$levelSums = [];
// BFS loop
while (!empty($queue)) {
$levelSize = count($queue);
$currentLevelSum = 0;
// Process each node in the current level
for ($i = 0; $i < $levelSize; $i++) {
$node = array_shift($queue);
$currentLevelSum += $node->val;
// Add left and right children to the queue for the next level
if ($node->left !== null) {
array_push($queue, $node->left);
}
if ($node->right !== null) {
array_push($queue, $node->right);
}
}
// Store the sum of the current level
array_push($levelSums, $currentLevelSum);
}
// Sort the level sums in descending order
rsort($levelSums);
// Return the k-th largest level sum
return isset($levelSums[$k - 1]) ? $levelSums[$k - 1] : -1;
}
// Example 1:
// Input: root = [5,8,9,2,1,3,7,4,6], k = 2
$root1 = new TreeNode(5);
$root1->left = new TreeNode(8);
$root1->right = new TreeNode(9);
$root1->left->left = new TreeNode(2);
$root1->left->right = new TreeNode(1);
$root1->right->left = new TreeNode(3);
$root1->right->right = new TreeNode(7);
$root1->left->left->left = new TreeNode(4);
$root1->left->left->right = new TreeNode(6);
echo kthLargestLevelSum($root1, 2); // Output: 13
// Example 2:
// Input: root = [1,2,null,3], k = 1
$root2 = new TreeNode(1);
$root2->left = new TreeNode(2);
$root2->left->left = new TreeNode(3);
echo kthLargestLevelSum($root2, 1); // Output: 3
?> Explanation:
Time Complexity:
Space Complexity:
This approach ensures that we traverse the tree efficiently and return the correct kth largest level sum. |
Beta Was this translation helpful? Give feedback.
We'll follow these steps:
Let's implement this solution in PHP: 2583. Kth Largest Sum in a Binary Tree