Skip to content

Commit 4b4da2e

Browse files
authored
Merge pull request #3563 from aadil42/patch-99
Create 1457-pseudo-palindromic-paths-in-a-binary-tree.js
2 parents 2623063 + 2ea31ec commit 4b4da2e

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/**
2+
*
3+
* Definition for a binary tree node.
4+
* function TreeNode(val, left, right) {
5+
* this.val = (val===undefined ? 0 : val)
6+
* this.left = (left===undefined ? null : left)
7+
* this.right = (right===undefined ? null : right)
8+
* }
9+
*/
10+
/**
11+
* DFS | Hashing | Backtraking | tree-traversal
12+
* Time O(n) | Space O(n)
13+
* https://leetcode.com/problems/pseudo-palindromic-paths-in-a-binary-tree/
14+
* @param {TreeNode} root
15+
* @return {number}
16+
*/
17+
var pseudoPalindromicPaths = function(root) {
18+
19+
const addNum = (num, hashSet) => {
20+
hashSet[num] = (hashSet[num] + 1) || 1;
21+
}
22+
23+
const removeNum = (num, hashSet) => {
24+
hashSet[num] = hashSet[num] - 1;
25+
if (hashSet[num] === 0) delete hashSet[num];
26+
}
27+
28+
const isPalindrome = (hashSet) => {
29+
30+
let oddOccurances = 0;
31+
32+
for (const key in hashSet) {
33+
if (hashSet[key] % 2) oddOccurances++;
34+
}
35+
36+
return oddOccurances < 2;
37+
}
38+
39+
const dfs = (node, hashSet) => {
40+
if (!node.left && !node.right && isPalindrome(hashSet)) return 1;
41+
if (!node.left && !node.right) return 0;
42+
43+
let total = 0;
44+
if (node.left) {
45+
addNum(node.left.val, hashSet);
46+
total += dfs(node.left, hashSet);
47+
removeNum(node.left.val, hashSet);
48+
}
49+
50+
if (node.right) {
51+
addNum(node.right.val, hashSet);
52+
total += dfs(node.right, hashSet);
53+
removeNum(node.right.val, hashSet);
54+
}
55+
56+
return total;
57+
}
58+
59+
return dfs(root, {[root.val]: 1} \);
60+
61+
};

0 commit comments

Comments
 (0)