2641. Cousins in Binary Tree II
T: O(n)
S: O(n)
/**
* 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 {
//private record NodeInfo(TreeNode node, TreeNode parent){};
public TreeNode replaceValueInTree(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
List<Integer> levelSumList = new ArrayList<>();
while (!queue.isEmpty()) {
int qSize = queue.size();
int levelSum = 0;
for (int q = 0; q < qSize; q++) {
TreeNode cur = queue.poll();
levelSum += cur.val;
if (cur.left != null) {
queue.offer(cur.left);
}
if (cur.right != null) {
queue.offer(cur.right);
}
}
levelSumList.add(levelSum);
}
int level = 1;
queue.offer(root);
while (!queue.isEmpty()) {
int qSize = queue.size();
for (int q = 0; q < qSize; q++) {
TreeNode cur = queue.poll();
int sibilingSum = (cur.left == null ? 0 : cur.left.val) + (cur.right == null ? 0 : cur.right.val);
if (cur.left != null) {
cur.left.val = levelSumList.get(level) - sibilingSum; // get levelSumList here, and then it won't out of index
queue.offer(cur.left);
}
if (cur.right != null) {
cur.right.val = levelSumList.get(level) - sibilingSum;
queue.offer(cur.right);
}
}
level++;
}
root.val = 0;
return root;
}
}
/**
BFS 2 pass
T: O(n)
S: O(n)
levelsum
5.
next_level_sum - left - right
13
18
*/
Last updated