1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-14 18:07:32 +01:00
LeetCode/cpp/pseudo-palindromic-paths-in-a-binary-tree.cpp

60 lines
1.5 KiB
C++
Raw Normal View History

#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);
}
};