Skip to content

Commit 32a324e

Browse files
committed
Added Pseudo-Palindromic Paths in a Binary Tree.java
1 parent e7f4a8f commit 32a324e

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode() {}
8+
* TreeNode(int val) { this.val = val; }
9+
* TreeNode(int val, TreeNode left, TreeNode right) {
10+
* this.val = val;
11+
* this.left = left;
12+
* this.right = right;
13+
* }
14+
* }
15+
*/
16+
class Solution {
17+
public int pseudoPalindromicPaths (TreeNode root) {
18+
int[] map = new int[10];
19+
int[] count = {0};
20+
pseudoPalindromicPathsUtil(root, map, count);
21+
return count[0];
22+
}
23+
24+
private boolean isPalindrome(int[] map) {
25+
boolean oddFound = false;
26+
for(int i = 1; i <= 9; i++) {
27+
if (map[i] % 2 != 0) {
28+
if (oddFound) {
29+
return false;
30+
}
31+
oddFound = true;
32+
}
33+
}
34+
return true;
35+
}
36+
37+
private void pseudoPalindromicPathsUtil(TreeNode root, int[] map, int[] count) {
38+
if (root == null) {
39+
return;
40+
}
41+
map[root.val] = map[root.val] + 1;
42+
if (root.left == null && root.right == null) {
43+
if (isPalindrome(map)) {
44+
count[0]++;
45+
}
46+
}
47+
pseudoPalindromicPathsUtil(root.left, map, count);
48+
pseudoPalindromicPathsUtil(root.right, map, count);
49+
map[root.val] = map[root.val] - 1;
50+
}
51+
}

0 commit comments

Comments
 (0)