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:
parent
848381110f
commit
da19846d3f
1 changed files with 59 additions and 0 deletions
59
cpp/pseudo-palindromic-paths-in-a-binary-tree.cpp
Normal file
59
cpp/pseudo-palindromic-paths-in-a-binary-tree.cpp
Normal 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);
|
||||
}
|
||||
};
|
Loading…
Reference in a new issue