Home >Backend Development >PHP Tutorial >Kth Largest Sum in a Binary Tree
2583. Kth Largest Sum in a Binary Tree
Difficulty: Medium
Topics: Tree, Breadth-First Search, Sorting, 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:
Example 2:
Constraints:
Hint:
Solution:
We'll follow these steps:
Let's implement this solution in PHP: 2583. Kth Largest Sum in a Binary Tree
val = $val; $this->left = $left; $this->right = $right; } } /** * @param TreeNode $root * @param Integer $k * @return Integer */ function kthLargestLevelSum($root, $k) { ... ... ... /** * go to ./solution.php */ } // 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:
TreeNode Class: We define the TreeNode class to represent a node in the binary tree, where each node has a value (val), a left child (left), and a right child (right).
BFS Traversal: The function kthLargestLevelSum uses a queue to perform a BFS traversal. For each level, we sum the values of the nodes and store the result in an array ($levelSums).
Sorting Level Sums: After traversing the entire tree and calculating the level sums, we sort the sums in descending order using rsort. This allows us to easily access the k-th largest sum.
Edge Case Handling: If there are fewer than k levels, we return -1.
Time Complexity:
This approach ensures that we traverse the tree efficiently and return the correct kth largest level sum.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
The above is the detailed content of Kth Largest Sum in a Binary Tree. For more information, please follow other related articles on the PHP Chinese website!