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 in Binary Tree INPUT Binary Tree Structure 2 3 1 3 1 1 = Leaf Node Array Representation: [2, 3, 1, 3, 1, null, 1] ALGORITHM (DFS) 1 Use Bitmask Track digit counts with XOR 2 DFS Traversal path ^= (1 << node.val) 3 Check Leaf If leaf: check palindrome 4 Palindrome Check path & (path-1) == 0 Path Analysis: 2-->3-->3: [2,3,3] Palindrome: 3-2-3 [OK] 2-->3-->1: [2,3,1] Not Palindrome 2-->1-->1: [2,1,1] Palindrome: 1-2-1 [OK] FINAL RESULT Valid Pseudo-Palindromic Paths Path 1: 2 --> 3 --> 3 Permutation: 3-2-3 [OK] Palindrome Path 2: 2 --> 1 --> 1 Permutation: 1-2-1 [OK] Palindrome Output: 2 2 valid paths found from root to leaves Key Insight: A path can form a palindrome if AT MOST ONE digit has an odd frequency. Using XOR bitmask: toggle bit for each digit. Valid palindrome if path has 0 or 1 bit set. Check: (path & (path - 1)) == 0 means at most one bit is set. Time: O(n), Space: O(h) TutorialsPoint - Pseudo-Palindromic Paths in a Binary Tree | DFS with Bitmask
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