mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-10 00:09:06 +01:00
60 lines
1.5 KiB
C++
60 lines
1.5 KiB
C++
|
#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);
|
||
|
}
|
||
|
};
|