#include <array>

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
 * right(right) {}
 * };
 */
class Solution {
    static auto leaf(TreeNode *node) -> bool {
        return node != nullptr &&
               (node->left == nullptr && node->right == nullptr);
    }

    static auto palindrome(const std::array<int, 10> &counters) -> bool {
        int odd = 0;

        for (int d = 1; d < 10; ++d) {
            if (counters[d] % 2 == 1) {
                ++odd;
            }
        }

        return odd <= 1;
    }

    static auto pseudoPalindromicPaths(TreeNode *node,
                                       std::array<int, 10> &counters) -> int {
        if (node == nullptr) {
            return counters[0];
        }

        ++counters[node->val];

        if (leaf(node) && palindrome(counters)) {
            ++counters[0];
        }

        pseudoPalindromicPaths(node->left, counters);
        pseudoPalindromicPaths(node->right, counters);

        --counters[node->val];
        return counters[0];
    }

  public:
    int pseudoPalindromicPaths(TreeNode *root) {
        std::array<int, 10> counters;
        counters.fill(0);

        return pseudoPalindromicPaths(root, counters);
    }
};