Pseudo-Palindromic Paths in a Binary Tree Problem
Description
LeetCode Problem 1457.
Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be pseudo-palindromic if at least one permutation of the node values in the path is a palindrome.
Return the number of pseudo-palindromic paths going from the root node to leaf nodes.
Example 1:

Input: root = [2,3,1,3,1,null,1]
Output: 2
Explanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the red path [2,3,3], the green path [2,1,1], and the path [2,3,1]. Among these paths only red path and green path are pseudo-palindromic paths since the red path [2,3,3] can be rearranged in [3,2,3] (palindrome) and the green path [2,1,1] can be rearranged in [1,2,1] (palindrome).
Example 2:

Input: root = [2,1,1,1,3,null,null,null,null,null,1]
Output: 1
Explanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the green path [2,1,1], the path [2,1,3,1], and the path [2,1]. Among these paths only the green path is pseudo-palindromic since [2,1,1] can be rearranged in [1,2,1] (palindrome).
Example 3:
Input: root = [9]
Output: 1
Constraints:
- The number of nodes in the tree is in the range
[1, 10^5]. 1 <= Node.val <= 9
Solution
Approach: DFS with a Parity Bitmask
A list of digits can be rearranged into a palindrome exactly when at most one digit appears an odd number of times (that digit, if any, goes in the middle). So for a path we only need to know, for each digit, whether its count is odd or even.
Keep that as a bitmask: bit v is 1 when digit v has appeared an odd number of times. Visiting a node with value v flips bit v, which is mask ^= 1 << v.
Run a DFS from the root, passing the mask down. At a leaf, the path is pseudo-palindromic when at most one bit is set. The check mask & (mask - 1) == 0 does that: it clears the lowest set bit, so it is 0 exactly when mask has zero or one bits set.
Only leaves count as path ends: a node with one child is not the end of a root-to-leaf path, so we just recurse into its child.
Complexity: O(n) time and O(h) extra space for the recursion, where h is the height of the tree.
class Solution:
def pseudoPalindromicPaths(self, root: Optional[TreeNode]) -> int:
def dfs(node: Optional[TreeNode], mask: int) -> int:
# Bit v of mask is set when digit v has appeared an odd number of times on the path.
if node is None:
return 0
mask ^= 1 << node.val
if node.left is None and node.right is None:
# A permutation is a palindrome when at most one digit has an odd count.
return 1 if mask & (mask - 1) == 0 else 0
return dfs(node.left, mask) + dfs(node.right, mask)
return dfs(root, 0)