-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Time: 43 ms (16.1%), Space: 68.4 MB (11.72%) - LeetHub
- Loading branch information
1 parent
8654f7e
commit 6371814
Showing
1 changed file
with
47 additions
and
0 deletions.
There are no files selected for viewing
47 changes: 47 additions & 0 deletions
47
2583-kth-largest-sum-in-a-binary-tree/2583-kth-largest-sum-in-a-binary-tree.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
/** | ||
* Definition for a binary tree node. | ||
* public class TreeNode { | ||
* int val; | ||
* TreeNode left; | ||
* TreeNode right; | ||
* TreeNode() {} | ||
* TreeNode(int val) { this.val = val; } | ||
* TreeNode(int val, TreeNode left, TreeNode right) { | ||
* this.val = val; | ||
* this.left = left; | ||
* this.right = right; | ||
* } | ||
* } | ||
*/ | ||
class Solution { | ||
public long kthLargestLevelSum(TreeNode root, int k) { | ||
if (root == null) return 0L; | ||
ArrayList<ArrayList<Integer>> list = new ArrayList<>(); | ||
|
||
Queue<TreeNode> queue = new LinkedList<>(); | ||
queue.add(root); | ||
while (!queue.isEmpty()) { | ||
int levelSize = queue.size(); | ||
ArrayList<Integer> curr = new ArrayList<>(); | ||
for (int i = 0; i < levelSize; i++) { | ||
TreeNode node = queue.poll(); | ||
curr.add(node.val); | ||
if (node.left != null) queue.add(node.left); | ||
if (node.right != null) queue.add(node.right); | ||
} | ||
list.add(curr); | ||
} | ||
|
||
ArrayList<Long> levelSums = new ArrayList<>(); | ||
for (ArrayList<Integer> level : list) { | ||
long sum = 0L; | ||
for (int val : level) { | ||
sum += val; | ||
} | ||
levelSums.add(sum); | ||
} | ||
levelSums.sort((a, b) -> Long.compare(b, a)); | ||
|
||
return k <= levelSums.size() ? levelSums.get(k - 1) : -1L; | ||
} | ||
} |