Pseudo-Palindromic Paths in a Binary Tree (LeetCode 1457): Solution and Explanation

Medium
Bit Manipulation
Tree
Depth First Search
Breadth First Search
Binary Tree

Count root-to-leaf paths whose digits can be rearranged into a palindrome. A DFS carries one bitmask of digit parities and checks it at every leaf.

Intuition

A palindrome pairs up its characters from both ends. Every value must therefore appear an even number of times, except possibly one value that sits in the middle. So a path qualifies exactly when at most one digit has an odd count.

That test only needs to know whether each digit's count is odd or even, not the counts themselves. With digits 1 to 9 there are nine yes/no facts, which fit in the bits of one integer.

Stepping onto a node with value v flips bit v with XOR. Because the mask is passed down by value, returning from a child restores the parent's mask with no extra work. At a leaf, mask & (mask - 1) clears the lowest set bit, so it is zero exactly when at most one bit was set.

Approach: DFS with a parity bitmask

  1. Call dfs(root, 0).
  2. If the node is null, return 0.
  3. Flip the node's digit: mask ^= 1 << node.val.
  4. If the node is a leaf, return 1 when mask & (mask - 1) == 0, else 0.
  5. Otherwise return dfs(left, mask) + dfs(right, mask).

Step-by-step example

root = [2,3,1,3,1,null,1]
  1. At the root 2 the mask has only bit 2 set.
  2. Going left to 3 sets bit 3. At the leaf 3, bit 3 flips back off, leaving only bit 2: one odd digit, so [2,3,3] counts. Count = 1.
  3. At the leaf 1 under 3, bit 1 turns on, so bits 1, 2 and 3 are set: three odd digits, so [2,3,1] does not count.
  4. On the right, 1 sets bit 1 and the leaf 1 clears it again, leaving only bit 2. [2,1,1] counts. Count = 2.
  5. All leaves are checked, so the answer is 2.

Code: Python, Java, C++

1class Solution:
2    def pseudoPalindromicPaths(self, root: Optional[TreeNode]) -> int:
3        def dfs(node, mask):
4            if not node:
5                return 0
6            mask ^= 1 << node.val
7            if not node.left and not node.right:
8                return 1 if mask & (mask - 1) == 0 else 0
9            return dfs(node.left, mask) + dfs(node.right, mask)
10
11        return dfs(root, 0)
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each node is visited once and does a constant amount of bit work.

Space

O(h)

Only the recursion stack is used, as deep as the tree height h.

Other approaches

Count array with backtracking (time O(9n), space O(h))

Keep an array of nine counts, increment on entry and decrement on exit, and at each leaf count how many entries are odd. Same idea with more bookkeeping.

Iterative DFS with a stack of (node, mask) (time O(n), space O(h))

Push pairs of a node and the mask above it onto an explicit stack. It avoids recursion depth limits on very skewed trees.

Common mistakes

  • Checking the condition at every node instead of only at leaves. Only complete root-to-leaf paths count.
  • Treating a node with one child as a leaf. A leaf has no children at all.
  • Using a shared mutable count array without undoing the change when returning from a child.
  • Testing mask == 0 only. One odd digit is allowed, because it can sit in the middle of the palindrome.

Frequently asked questions

Why does mask & (mask - 1) == 0 mean at most one odd digit?

Subtracting 1 flips the lowest set bit and everything below it, so the AND clears exactly that bit. The result is zero only if there was no other set bit.

Why do I not need to undo the XOR on the way back up?

The mask is an integer passed by value. Each call works on its own copy, so the parent's mask is unchanged when the child returns.

Does the order of values on the path matter?

No. The question is whether the values can be rearranged into a palindrome, which depends only on how many times each digit appears.