Skip to content

Commit a9c9e8d

Browse files
Create 1457-pseudo-palindromic-paths-in-a-binary-tree.java
1 parent a7603b5 commit a9c9e8d

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution {
2+
Map<Integer, Integer> count = new HashMap<>();
3+
int odd = 0;
4+
5+
public int pseudoPalindromicPaths(TreeNode root) {
6+
return dfs(root);
7+
}
8+
9+
private int dfs(TreeNode curr) {
10+
if (curr == null) {
11+
return 0;
12+
}
13+
14+
count.put(curr.val, count.getOrDefault(curr.val, 0) + 1);
15+
int oddChange = count.get(curr.val) % 2 == 1 ? 1 : -1;
16+
odd += oddChange;
17+
18+
int res = 0;
19+
if (curr.left == null && curr.right == null) {
20+
res = (odd <= 1) ? 1 : 0;
21+
} else {
22+
res = dfs(curr.left) + dfs(curr.right);
23+
}
24+
25+
odd -= oddChange;
26+
count.put(curr.val, count.get(curr.val) - 1);
27+
return res;
28+
}
29+
}

0 commit comments

Comments
 (0)