forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1457-pseudo-palindromic-paths-in-a-binary-tree.js
61 lines (49 loc) · 1.53 KB
/
1457-pseudo-palindromic-paths-in-a-binary-tree.js
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
54
55
56
57
58
59
60
61
/**
*
* 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)
* }
*/
/**
* DFS | Hashing | Backtraking | tree-traversal
* Time O(n) | Space O(n)
* https://leetcode.com/problems/pseudo-palindromic-paths-in-a-binary-tree/
* @param {TreeNode} root
* @return {number}
*/
var pseudoPalindromicPaths = function(root) {
const addNum = (num, hashSet) => {
hashSet[num] = (hashSet[num] + 1) || 1;
}
const removeNum = (num, hashSet) => {
hashSet[num] = hashSet[num] - 1;
if (hashSet[num] === 0) delete hashSet[num];
}
const isPalindrome = (hashSet) => {
let oddOccurances = 0;
for (const key in hashSet) {
if (hashSet[key] % 2) oddOccurances++;
}
return oddOccurances < 2;
}
const dfs = (node, hashSet) => {
if (!node.left && !node.right && isPalindrome(hashSet)) return 1;
if (!node.left && !node.right) return 0;
let total = 0;
if (node.left) {
addNum(node.left.val, hashSet);
total += dfs(node.left, hashSet);
removeNum(node.left.val, hashSet);
}
if (node.right) {
addNum(node.right.val, hashSet);
total += dfs(node.right, hashSet);
removeNum(node.right.val, hashSet);
}
return total;
}
return dfs(root, {[root.val]: 1} \);
};