-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0663-equal-tree-partition.js
More file actions
35 lines (28 loc) · 995 Bytes
/
0663-equal-tree-partition.js
File metadata and controls
35 lines (28 loc) · 995 Bytes
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
/**
* Equal Tree Partition
* Time Complexity: O(N)
* Space Complexity: O(N)
*/
var checkEqualTree = function (root) {
const allRecordedSubtreeSums = new Set();
const calculateSubtreeSumAndRecord = (currentTreeNode) => {
if (!currentTreeNode) {
return 0;
}
const sumFromLeftChild = calculateSubtreeSumAndRecord(currentTreeNode.left);
const sumFromRightChild = calculateSubtreeSumAndRecord(
currentTreeNode.right,
);
const currentPathSum =
currentTreeNode.val + sumFromLeftChild + sumFromRightChild;
if (currentTreeNode !== root) {
allRecordedSubtreeSums.add(currentPathSum);
}
return currentPathSum;
};
const fullTreeOverallSum = calculateSubtreeSumAndRecord(root);
const isTotalSumDivisibleByTwo = fullTreeOverallSum % 2 === 0;
const targetHalfSumValue = fullTreeOverallSum / 2;
const doesHalfSumExist = allRecordedSubtreeSums.has(targetHalfSumValue);
return isTotalSumDivisibleByTwo && doesHalfSumExist;
};