tree
dfs
palindrome
bit manipulation
]
Leetcode 1457. Pseudo-Palindromic Paths in a Binary Tree
https://leetcode.com/problems/pseudo-palindromic-paths-in-a-binary-tree
First note, that pseudo-palindromic path mean that it has all occurunces of digits even, may be except one: like 11223 can be written as 12321 and 111444 can not, because it has two digits with odd occurences. So, for each leaf we need to evaluate occurences of all digits and count it only if number of odd occurences is <=1.
Let dict_freq
be a frequences dictionary for digits, where we keep 0 if we meet digit even number of times and 1 if we meet digit odd number of times. Let Pal
be a variable, which counts number of odd frequences in dict_freq
: we want to find all leafs, for which this value is <= 1.
Now, what we do is simple dfs: preorder traversal. Because dict_freq
is global variable and we change it in our recursion, we need to change back it values, when we go outside of recursion (note, that in some other solutions, which use bit manipulations, it is not necessary, but here we need to do like this). Finally, because we do only O(1) operations for each node, we have O(n) time complexity. We have O(k+H) space complexity, where H is the height of tree and k is number of digits (here k = 9) to maintain implicit stack and dict_freq
dictionary.
class Solution:
def dfs(self, root):
if not root: return
cur, pal = self.dict_freq[root.val], self.Pal
self.Pal = self.Pal - 1 if cur == 1 else self.Pal + 1
self.dict_freq[root.val] = (cur + 1) % 2
if not root.left and not root.right and self.Pal <= 1:
self.Res += 1
self.dfs(root.left)
self.dfs(root.right)
self.Pal, self.dict_freq[root.val] = pal, cur
def pseudoPalindromicPaths (self, root):
self.dict_freq = defaultdict(int)
self.Pal, self.Res = 0, 0
self.dfs(root)
return self.Res
If you like the solution, you can upvote it on leetcode discussion section: Problem 1457