Kth Largest Sum in a Binary Tree
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 $k^{th}$ largest level sum in the tree (not necessary distinct). If there are fewer than $k$ levels in the tree, return -1.
Example:
1 | Input: root = [5, 8, 9, 2, 1, 3, 7, 4, 6], k = 2; |
1 | Input: root = [1, 2, null, 3], k = 1; |
Constraints:
- The number of nodes in the tree is $n$.
- $2 \le Node.val \le 10^5 $
- $1 \le k \le n$
Solution
1 | struct TreeNode { |
Explanation:
Since this problem needs us to calculate the sum of each level of the binary tree, a breadth-first traversal is required. The most used method for breadth-first traversal is to use a queue, the CPP style example code is this:
1 | void printTreeBreadthFirst(TreeNode* root) { |
In this problem, the variable $n$ holds the number of nodes in this level, which $n$ equals current size of the queue. Thus, it only needs to use a inner loop to calculate the sum of the level by popping values from the queue, and meanwhile import the nodes of the next level by accessing the children of current head node of the queue.