1+ Given a binary tree where node values are digits from 1 to 9.
2+ A path in the binary tree is said to be pseudo - palindromic if
3+ at least one permutation of the node values in the path is a palindrome .
4+
5+ Return the number of pseudo - palindromic paths going from the root node to leaf nodes .
6+
7+ Example 1 :
8+ Input : root = [2 ,3 ,1 ,3 ,1 ,null ,1 ]
9+ Output : 2
10+ Explanation : The figure above represents the given binary tree .
11+ There are three paths going from the root node to leaf nodes :
12+ the red path [2 ,3 ,3 ], the green path [2 ,1 ,1 ], and the path [2 ,3 ,1 ].
13+ Among these paths only red path and green path are pseudo - palindromic p
14+ aths since the red path [2 ,3 ,3 ] can be rearranged in [3 ,2 ,3 ] (palindrome )
15+ and the green path [2 ,1 ,1 ] can be rearranged in [1 ,2 ,1 ] (palindrome ).
16+
17+ Example 2 :
18+ Input : root = [2 ,1 ,1 ,1 ,3 ,null ,null ,null ,null ,null ,1 ]
19+ Output : 1
20+ Explanation : The figure above represents the given binary tree .
21+ There are three paths going from the root node to leaf nodes :
22+ the green path [2 ,1 ,1 ], the path [2 ,1 ,3 ,1 ], and the path [2 ,1 ].
23+ Among these paths only the green path is pseudo - palindromic
24+ since [2 ,1 ,1 ] can be rearranged in [1 ,2 ,1 ] (palindrome ).
25+
26+ Example 3 :
27+ Input : root = [9 ]
28+ Output : 1
29+
30+
31+ Constraints :
32+ The given binary tree will have between 1 and 10 ^ 5 nodes .
33+ Node values are digits from 1 to 9.
34+
35+ Hint #1
36+ Note that the node values of a path form a palindrome if
37+ at most one digit has an odd frequency (parity ).
38+
39+ Hint #2
40+ Use a Depth First Search (DFS ) keeping the frequency (parity ) of the digits .
41+ Once you are in a leaf node check if at most one digit has an odd frequency (parity ).
42+
43+
44+ # Definition for a binary tree node.
45+ # class TreeNode:
46+ # def __init__(self, val=0, left=None, right=None):
47+ # self.val = val
48+ # self.left = left
49+ # self.right = right
50+
51+
52+ # O(n) Time and O(h) Space
53+ class Solution :
54+ def pseudoPalindromicPaths (self , root : TreeNode ) - > int :
55+
56+ self .result = 0
57+
58+ self .digits = [0 for i in range (10 )]
59+
60+
61+ self .dfs (root )
62+
63+ return self .result
64+
65+ def isPalindrome (self ):
66+
67+ is_odd = 0
68+
69+ for i in range (10 ):
70+ if self .digits [i ] % 2 != 0 :
71+ is_odd + = 1
72+
73+ if is_odd > 1 :
74+ return False
75+
76+ return True
77+
78+ def dfs (self , root ):
79+ if root is None :
80+ return
81+
82+ self .digits [root .val ] + = 1
83+
84+ if not root .right and not root .left :
85+
86+ if self .isPalindrome ():
87+ self .result + = 1
88+ else :
89+ self .dfs (root .left )
90+ self .dfs (root .right )
91+
92+ self .digits [root .val ] - = 1
0 commit comments