-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path2641-cousins-in-binary-tree-ii.js
More file actions
53 lines (47 loc) · 1.47 KB
/
2641-cousins-in-binary-tree-ii.js
File metadata and controls
53 lines (47 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
* 2641. Cousins in Binary Tree II
* https://leetcode.com/problems/cousins-in-binary-tree-ii/
* Difficulty: Medium
*
* Given the root of a binary tree, replace the value of each node in the tree with the
* sum of all its cousins' values.
*
* Two nodes of a binary tree are cousins if they have the same depth with different parents.
*
* Return the root of the modified tree.
*
* Note that the depth of a node is the number of edges in the path from the root node to it.
*/
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
var replaceValueInTree = function(root) {
const levelSums = [];
collectSums(root, 0);
replaceValues(root, 0, 0);
return root;
function collectSums(node, depth) {
if (!node) return;
if (levelSums.length <= depth) levelSums.push(0);
levelSums[depth] += node.val;
collectSums(node.left, depth + 1);
collectSums(node.right, depth + 1);
}
function replaceValues(node, depth, siblingSum) {
if (!node) return;
node.val = levelSums[depth] - node.val - siblingSum;
const leftVal = node.left ? node.left.val : 0;
const rightVal = node.right ? node.right.val : 0;
replaceValues(node.left, depth + 1, rightVal);
replaceValues(node.right, depth + 1, leftVal);
}
};