Pseudo-Palindromic Paths in a Binary Tree solution explained

To count pseudo-palindromic paths in a binary tree, walk from the root to every leaf while keeping a 9-bit mask where bit d records whether digit d has appeared an odd number of times so far; flip that bit at each node. At a leaf, the path can be rearranged into a palindrome exactly when at most one bit is set, which the test mask & (mask - 1) == 0 checks in constant time. The walk is O(n) time with O(h) extra space.

By Published 8 min read

The problem, rephrased

Each node of a binary tree holds one digit from 1 to 9. Follow any path from the root down to a leaf, a node without children, and write down the digits you pass. That path is called pseudo-palindromic if its digits, shuffled into some order, read the same forwards and backwards. You do not need to find the order, only to know whether one exists. Return how many root-to-leaf paths qualify.

         3
        / \
       1   3
      / \    \
     1   2    9

3-1-1: one 3, two 1s       -> 1 3 1 works        yes
3-1-2: one each of 3, 1, 2 -> three odd counts    no
3-3-9: two 3s, one 9       -> 3 9 3 works        yes
Answer: 2
A tree made up for this page

The whole problem rests on one fact about palindromes. In a palindrome, every character pairs with its mirror image, except possibly one character in the very middle. So a bag of digits can be arranged into a palindrome exactly when at most one digit occurs an odd number of times. Paths of even length need zero odd counts; paths of odd length need exactly one. The rule "at most one" covers both.

Why it appears in interviews

It combines a familiar tree walk with a bit of number sense. The interviewer is looking for three things: that you reduce "can be rearranged into a palindrome" to a parity check instead of trying permutations, that you carry state from the root down rather than rebuilding it at each leaf, and that you know a compact way to test "at most one bit set". Likely follow-ups:

  • Values are any integers, not digits. A bitmask no longer fits, so carry a set of values with odd counts and add or remove as you go, undoing on the way back up.
  • Return the paths, not the count. Keep the path list alongside the mask.
  • Any downward path, not only root to leaf. Count prefix masks seen on the current root path, the same idea as counting subarrays with a target sum.
  • Letters instead of digits. Use 26 bits; the trick is unchanged.
  • Explain mask & (mask - 1). It clears the lowest set bit, so the result is zero only if there was at most one set bit.

Direct approach: count each path at its leaf

A clear first answer keeps the current path in a list during a depth-first walk. At each leaf, count the digits and check how many occur an odd number of times. Pop the node off the list when returning. It is correct and easy to explain, but each leaf does work proportional to its depth, so the total is O(n·h), which reaches O(n²) on a tall tree.

from collections import Counter

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

def count_paths_by_counting(root):
    total = 0

    def walk(node, path):
        nonlocal total
        path.append(node.val)
        if node.left is None and node.right is None:
            odd = sum(1 for c in Counter(path).values() if c % 2)
            if odd <= 1:
                total += 1
        else:
            if node.left:
                walk(node.left, path)
            if node.right:
                walk(node.right, path)
        path.pop()

    if root:
        walk(root, [])
    return total
Python: path list plus a Counter at each leaf. O(n·h). Our test reference.

Optimal approach: a parity bitmask

We never need the actual counts, only whether each is odd or even. Nine digits means nine yes-or-no flags, which fit in the bits of one integer. Start at 0. When the walk enters a node holding digit d, flip bit d with XOR. Two visits to the same digit flip the bit twice and cancel. At a leaf, the mask has a 1 exactly for the digits seen an odd number of times on that path.

Testing "at most one bit set" is the classic power-of-two check. Subtracting 1 from a number turns its lowest set bit into 0 and the zeros below it into 1s, so mask & (mask - 1) removes that lowest bit. If the result is 0, there was at most one bit to begin with. Because the mask is passed down as a value, every branch automatically gets its own copy and nothing needs undoing.

def pseudo_palindromic_paths(root):
    def walk(node, mask):
        if node is None:
            return 0
        mask ^= 1 << node.val
        if node.left is None and node.right is None:
            return 1 if mask & (mask - 1) == 0 else 0
        return walk(node.left, mask) + walk(node.right, mask)

    return walk(root, 0)
Python: DFS carrying a 9-bit parity mask. O(n) time, O(h) stack.

This recursive form gives up on trees deeper than Python's default limit of roughly a thousand frames. The JavaScript version stores pairs of node and parent mask on an explicit stack instead, so a very tall tree causes no trouble. JavaScript's bitwise operators work on 32-bit integers, which is plenty for nine flags.

function pseudoPalindromicPaths(root) {
  if (root === null) return 0;
  let count = 0;
  const stack = [[root, 0]];
  while (stack.length > 0) {
    const [node, parentMask] = stack.pop();
    const mask = parentMask ^ (1 << node.val);
    if (node.left === null && node.right === null) {
      if ((mask & (mask - 1)) === 0) count++;
    } else {
      if (node.left !== null) stack.push([node.left, mask]);
      if (node.right !== null) stack.push([node.right, mask]);
    }
  }
  return count;
}
JavaScript: iterative DFS with the parity mask. O(n) time.

Trace the left path of the example in bits, writing only bits 3, 2 and 1. Entering 3 sets bit 3: 100. Entering 1 sets bit 1: 101. Entering the leaf 1 clears bit 1: 100. One bit is set, so it counts. The path 3-1-2 ends at 111, three bits, so it does not. The right path 3-3-9 ends with only bit 9 set, so it counts. Total 2.

Complexity

n nodes, height h, digits 1 to 9
ApproachTimeExtra space
Path list, count at each leafO(n·h)O(h) for the path and stack
Count array of 10 plus an odd-count tally, undo on returnO(n)O(h) stack plus O(1) array
Parity bitmask, recursiveO(n)O(h) call stack
Parity bitmask, explicit stackO(n)O(h) to O(n) for the stack
n nodes, height h, digits 1 to 9. Scroll sideways on a small screen.

Edge cases

  • A single node: one path of one digit, always pseudo-palindromic, so the answer is 1.
  • A node with one child: not a leaf, so its partial path is not counted.
  • All digits equal: every root-to-leaf path qualifies.
  • Every path with all-distinct digits and length at least 2: the answer is 0.
  • A tall chain: one path, and a stress test for recursion depth.

Common mistakes

  • Checking whether the path is a palindrome as written, rather than whether some reordering is.
  • Requiring zero odd counts, which rejects every odd-length palindrome like 1 3 1.
  • Counting at null children, so a node with one child adds a partial path.
  • Sharing one count array between branches without undoing changes on the way back.
  • Leaving out the parentheses around the AND in JavaScript (mask & (mask - 1) === 0) or C and C++ (the same with ==). Equality binds more tightly there, so the expression compares first and masks second. Java rejects the bare form at compile time, and Python happens to parse it the intended way.

Explaining it out loud

Fictional example

From palindromes to bits
Candidate
A set of digits can be rearranged into a palindrome if at most one digit appears an odd number of times, so I only need parities.
Candidate
I will carry a nine-bit mask down from the root and XOR in each digit. At a leaf, the set bits are the digits with odd counts.
Interviewer
How do you check the mask?
Candidate
mask and mask minus one clears the lowest set bit. If that leaves zero, at most one bit was set, so the path counts.
Candidate
Every node does constant work, so it is O(n) time and the stack is as deep as the tree.

Sum Root to Leaf Numbers carries a number down the same root-to-leaf paths, and Longest ZigZag Path in a Binary Tree carries two counters. Most Frequent Subtree Sum works in the opposite direction, from the leaves up. For more bit tricks, Single Number uses XOR in the same cancel-in-pairs way.

Practice support from Natively

Natively can take a screenshot of a problem like this during a practice session on Mac or Windows and respond with an approach and code in its overlay, or answer a single question, such as why XOR captures parity, if that is all you want. It also transcribes your spoken explanation in a mock interview, so you can check later whether the palindrome rule came out before the bit trick. Read more about the AI interview assistant.

Questions people ask

How do you count pseudo-palindromic paths in a binary tree?

Walk from the root to each leaf, flipping bit d of a mask whenever you pass digit d. At a leaf, the path qualifies if at most one bit is set, which mask & (mask - 1) == 0 checks.

When can a set of digits be rearranged into a palindrome?

When at most one digit occurs an odd number of times. Every other digit must pair up around the center.

What is the time complexity of Pseudo-Palindromic Paths?

O(n) time, since each node does a constant amount of work, and O(h) extra space for the recursion or stack.

What does mask & (mask - 1) do?

It clears the lowest set bit. If the result is zero, the mask had at most one bit set, meaning at most one digit has an odd count.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP