1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-09 15:59:06 +01:00

cpp: add “1457. Pseudo-Palindromic Paths in a Binary Tree”

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-01-24 09:27:08 +01:00
parent 848381110f
commit da19846d3f
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -0,0 +1,59 @@
#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);
}
};