Pseudo-Palindromic Paths in a Binary Tree - Problem

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.

Note: A palindrome reads the same forward and backward. For example, 121 is a palindrome while 123 is not.

Input & Output

Example 1 — Basic Tree
$ Input: root = [2,3,1,3,1,null,1]
Output: 2
💡 Note: Path [2,3,3] has digits 2(×1), 3(×2) - only one odd count, can form palindrome '323'. Path [2,1,1] has digits 2(×1), 1(×2) - only one odd count, can form palindrome '121'. Path [2,3,1] has all odd counts - cannot form palindrome.
Example 2 — Single Path
$ Input: root = [2,1,1,1,3,null,null,null,null,null,1]
Output: 1
💡 Note: Only one root-to-leaf path exists: [2,1,1,1]. Digit frequencies: 2(×1), 1(×3). Only one digit has odd count, so palindrome '11211' is possible.
Example 3 — No Palindromes
$ Input: root = [9]
Output: 1
💡 Note: Single node path [9] has only one digit with count 1 (odd). Single digits are always palindromes.

Constraints

  • The number of nodes in the tree is in the range [1, 105]
  • 1 ≤ Node.val ≤ 9

Visualization

Tap to expand
Pseudo-Palindromic Paths: Find Rearrangeable Palindromes231311Path 1: [2,3,3]Frequencies: 2(×1), 3(×2)✓ Palindrome: '323'Path 2: [2,3,1]Frequencies: 2(×1), 3(×1), 1(×1)✗ All odd countsPath 3: [2,1,1]Frequencies: 2(×1), 1(×2)✓ Palindrome: '121'Palindrome Rule:At most 1 character can haveodd frequency countExamples: 'aba', 'racecar'Answer: 2 pseudo-palindromic paths found
Understanding the Visualization
1
Input Tree
Binary tree with digit values 1-9
2
Path Analysis
Check each root-to-leaf path for palindrome potential
3
Count Result
Return number of valid pseudo-palindromic paths
Key Takeaway
🎯 Key Insight: Use bit manipulation to efficiently track odd/even digit frequencies during DFS traversal
Asked in
Facebook 25 Amazon 20 Google 15 Microsoft 12
87.5K Views
Medium Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen