Problem 611
Pseudo-Palindromic Paths in a Binary Tree
Medium · 20 pts · Tree, Depth-First Search, Bit Manipulation
Problem
Every node holds a digit from 1 to 9. A root-to-leaf path is pseudo-palindromic if its values can be rearranged into a palindrome, which happens exactly when at most one digit appears an odd number of times on it. Count the pseudo-palindromic root-to-leaf paths. Keep a 9-bit mask of digit parities along the path, flipping bit d at a node with value d; at a leaf the path qualifies when the mask has at most one bit set.
Input
The first line contains N, the number of tokens. The second line contains N tokens describing the tree in level order (breadth-first, left to right), where 'null' marks a missing child, as on LeetCode.
Output
Print the number of pseudo-palindromic paths.
Constraints
1 <= number of nodes <= 100000; 1 <= value <= 9
Example input
7 2 3 1 3 1 null 1
Example output
2
Explanation
The tree 2 3 1 3 1 null 1 has three root-to-leaf paths: 2 3 3, 2 3 1 and 2 1 1. The first can become 3 2 3 and the third 1 2 1, but 2 3 1 cannot, so the answer is 2.