Given a binary tree and a non negative integer k. Find and return the Kth maximum level sum in a binary tree. If the levels are less than k, return -1.
Output: 13. Explanation: The sums of nodes at each level are: Level 1: 1 Level 2: 2 + 3 = 5 Level 3: 4 + 5 + 6 + 7 = 22 Level 4: 8 + 9 = 17 Level 5: 10 + 11 = 21 The 2nd largest level sum is 21.
Input: root = [7, 9, 10, 12, 13, 14, 16, 25, 30], k = 2 Output: 13. Explanation: The sums of nodes at each level are: Level 1: 7. Level 2: 9 + 10 = 19. Level 3: 12 + 13 + 14 + 16 = 55. Level 4: 30+ 40 = 70. The 2nd largest level sum is 55.
:
This can be solved using queue data structure afterwards keep finding the sum of each level and store the sum of each level in a vector say ans. Sort the ans array and print the kth maximum sum.
Below is the steps for above approach:
Create an empty queue q and push root in q.
Initialize vector ans.
Run while loop until q is not empty.
Initialize s=q.size()
Define a data structure vector V of size s
Run while loop until s-- .
Initialize temp = q.front() and store temp->data in V.
pop front node from q.
Push temp children i.e. temp->left then temp->right to q.
Initialize sum=0.
Add the element of V and store them in vector ans.
Sort the input array in the increasing order.
Return -1 if K-1 is equal or greater than ans.size() else return element at k-1 index.
Output
55
TimeComplexity: O(N log N), where N is the number of node in a binary tree. AuxiliarySpace: O(L), where L is the number of levels in a Binary tree.