forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPseudoPalindromicPathsInABinaryTree.java
More file actions
51 lines (38 loc) · 1004 Bytes
/
PseudoPalindromicPathsInABinaryTree.java
File metadata and controls
51 lines (38 loc) · 1004 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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Solution {
private int ans = 0;
// TC : O(n)
// SC : O(n) *10
public int pseudoPalindromicPaths (TreeNode root) {
int[] freq = new int[10];
helper(root, freq);
return ans;
}
private void helper(TreeNode root, int[] freq){
if(root== null){
return ;
}
freq[root.val]++;
if(root.left == null && root.right == null){
// this is a leaf node
if(isPalindromicPermutation(freq)){
ans++;
}
}
helper(root.left, freq);
helper(root.right, freq);
freq[root.val]--;
}
private boolean isPalindromicPermutation(int[] freq){
boolean oddFreqFound = false;
for(int el: freq){
if(el%2!=0){
if(oddFreqFound){
return false;
} else{
oddFreqFound = true;
}
}
}
return true;
}
}