java: add «2641. Cousins in Binary Tree II»
URL: https://leetcode.com/problems/cousins-in-binary-tree-ii/ Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
18e176c3e6
commit
29f2194d56
1 changed files with 51 additions and 0 deletions
51
java/cousins-in-binary-tree-ii.java
Normal file
51
java/cousins-in-binary-tree-ii.java
Normal file
|
@ -0,0 +1,51 @@
|
|||
class Solution {
|
||||
private int get(TreeNode node) {
|
||||
if (node == null) {
|
||||
return 0;
|
||||
}
|
||||
return node.val;
|
||||
}
|
||||
|
||||
private void handleNode(Queue<TreeNode> q, int siblings, TreeNode node) {
|
||||
if (node == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
node.val = siblings;
|
||||
q.offer(node);
|
||||
}
|
||||
|
||||
private int handleLevel(Queue<TreeNode> q, int previous) {
|
||||
int sum = 0;
|
||||
|
||||
for (int i = q.size(); i > 0; --i) {
|
||||
var node = q.poll();
|
||||
node.val = previous - node.val;
|
||||
|
||||
var siblings = get(node.left) + get(node.right);
|
||||
handleNode(q, siblings, node.left);
|
||||
handleNode(q, siblings, node.right);
|
||||
|
||||
sum += siblings;
|
||||
}
|
||||
|
||||
return sum;
|
||||
}
|
||||
|
||||
public TreeNode replaceValueInTree(TreeNode root) {
|
||||
if (root == null) {
|
||||
return root;
|
||||
}
|
||||
|
||||
Queue<TreeNode> q = new ArrayDeque<>();
|
||||
|
||||
int sumAbove = root.val;
|
||||
q.offer(root);
|
||||
|
||||
while (!q.isEmpty()) {
|
||||
sumAbove = handleLevel(q, sumAbove);
|
||||
}
|
||||
|
||||
return root;
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue