Pseudo-Palindromic Paths in a Binary Tree

Medium

Topics
TreeDFSBit Manipulation

Node values are digits 1-9. A root-to-leaf path is pseudo-palindromic if at least one permutation of its node values is a palindrome. Return the number of pseudo-palindromic root-to-leaf paths.

Example 1

331211
one pseudo-palindromic path
A path can be rearranged into a palindrome exactly when at most one value appears an odd number of times. Order never matters, so a 9-bit mask toggled per node captures the whole state, and the test is the one-liner m & (m-1) == 0. There are 2.
Tree given in level-order (breadth-first); null marks a missing child.
Input:  root = [2,3,1,3,1,null,1]
Output: 2

Example 2

113121
one pseudo-palindromic path
Input:  root = [2,1,1,1,3,null,null,null,null,null,1]
Output: 1

Constraints

  • 1 <= number of nodes <= 10^5
  • 1 <= Node.val <= 9
Editorial — intuition, approach, complexity and pitfalls

Intuition

A multiset of digits can be permuted into a palindrome exactly when at most one digit occurs an odd number of times. Nothing else about the path matters — not the order, not the actual counts, only each count's parity.

Parity is one bit per digit, and values are limited to 1–9, so the whole state fits in a nine-bit mask. XOR-ing 1 << val on the way down toggles that digit's parity, and because XOR is its own inverse the mask passed to a child is automatically restored for the sibling — there is nothing to undo. At a leaf, "at most one odd count" is the classic power-of-two test mask & (mask - 1) == 0.

Approach

  1. Descend with a mask, XOR-ing 1 << node.val at each node.
  2. At a leaf, count the path if mask & (mask - 1) == 0, which holds when the mask has zero or one bit set.
  3. Otherwise recurse into both children with the same mask value.

Dry Run

        2
      /   \
     3     1
    / \     \
   3   1     1

path 2->3->3   mask 0b100    mask & (mask-1) = 0    counts 2:1 3:2, one odd   -> yes
path 2->3->1   mask 0b1110   mask & (mask-1) = 12   counts 2:1 3:1 1:1        -> no
path 2->1->1   mask 0b100    mask & (mask-1) = 0    counts 2:1 1:2, one odd   -> yes

answer 2

Complexity

  • Time — O(n): one visit per node, constant work each.
  • Space — O(h) for the call stack, and h reaches n on a degenerate tree. At the stated bound of 10⁵ nodes that matters: a left-leaning path overflows Python's default limit of 1,000 and exceeds Node's stack somewhere between 5,000 and 10,000 frames. The Python harness on this page raises the limit for that reason; Java holds to roughly 20,000 frames by default, and an explicit stack is the portable answer.

Common Pitfalls

  • Carrying a count array and forgetting to decrement on the way back out. The XOR mask has no such failure mode, which is the real reason to prefer it over counting.
  • Testing for a palindrome by comparing the path to its reverse. The question asks whether some permutation is a palindrome, not whether this ordering is.
  • Requiring all counts even. One odd count is allowed — it becomes the middle character.
  • Checking the mask at internal nodes. Only root-to-leaf paths count, so the test belongs at nodes with no children.
  • Using 1 << node.val with a zero-based assumption. Values run 1–9, so bit 0 is simply never used; that is harmless but worth noticing before claiming the mask is nine bits.
  • Treating a node with one child as a leaf, which counts a path that does not reach a leaf.

Full Solution — all languages

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def pseudoPalindromicPaths(self, root):
        self.cnt = 0
        def dfs(node, mask):
            if not node: return
            mask ^= (1 << node.val)
            if not node.left and not node.right:
                if (mask & (mask - 1)) == 0: self.cnt += 1
                return
            dfs(node.left, mask); dfs(node.right, mask)
        dfs(root, 0)
        return self.cnt
SensAI
Beta
Tap the mic to stop voice mode