-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path0663-equal-tree-partition.js
More file actions
41 lines (35 loc) · 1.04 KB
/
0663-equal-tree-partition.js
File metadata and controls
41 lines (35 loc) · 1.04 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
/**
* 663. Equal Tree Partition
* https://leetcode.com/problems/equal-tree-partition/
* Difficulty: Medium
*
* Given the root of a binary tree, return true if you can partition the tree into two trees
* with equal sums of values after removing exactly one edge on the original tree.
*/
/**
* 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 {boolean}
*/
var checkEqualTree = function(root) {
const subtreeSums = new Set();
const totalSum = calculateSum(root);
return totalSum % 2 === 0 && subtreeSums.has(totalSum / 2);
function calculateSum(node) {
if (!node) return 0;
const leftSum = calculateSum(node.left);
const rightSum = calculateSum(node.right);
const currentSum = node.val + leftSum + rightSum;
if (node !== root) {
subtreeSums.add(currentSum);
}
return currentSum;
}
};