-
Notifications
You must be signed in to change notification settings - Fork 5
/
PseudoPalindromicPathsInABinaryTree.java
94 lines (85 loc) · 2.42 KB
/
PseudoPalindromicPathsInABinaryTree.java
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/*https://leetcode.com/problems/pseudo-palindromic-paths-in-a-binary-tree/*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int count;
int[] hash;
public int pseudoPalindromicPaths (TreeNode root) {
count = 0;
hash = new int[10];
solve(root);
return count;
}
private void solve(TreeNode root)
{
if (root == null) return;
if (root.left == null && root.right == null)
{
++hash[root.val];
int oddCount = 0;
for (int val : hash)
if (val%2 == 1)
++oddCount;
if (oddCount <= 1) ++count;
--hash[root.val];
return;
}
++hash[root.val];
solve(root.left);
solve(root.right);
--hash[root.val];
}
}
class Solution {
int count = 0;
public int pseudoPalindromicPaths (TreeNode root) {
findPaths(root, 0);
return count;
}
public void findPaths(TreeNode node, int oddeven)
{
if(node == null)
return;
oddeven = oddeven ^ (1 << node.val);
// leaf nodes
if(node.left == null && node.right == null)
{
// only one set bit/ odd count
if((oddeven & (oddeven-1)) == 0)
count++;
return;
}
findPaths(node.left, oddeven);
findPaths(node.right, oddeven);
}
// using oddeven int to store odd/even presence instead of another function since only 1-9 nums present and we dont need count but odd/even only
// private boolean isPseudoPalindromic(List<TreeNode> nodes)
// {
// boolean foundOdd = false;
// // values are from 0-9 given so noneed of hashmap
// int[] freq = new int[10];
// for(TreeNode node : nodes)
// freq[node.val]++;
// for(int i=0; i<freq.length; i++){
// if(freq[i] % 2 == 1){
// if(foundOdd)
// return false;
// foundOdd = true;
// }
// }
// return true;
// }
}