https://leetcode.cn/problems/pseudo-palindromic-paths-in-a-binary-tree/
/**
* 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 {
public:
int res = 0;
bool isPseudoPa(unordered_map<int,int> &curPath) {
int odd = 0;
for (auto it = curPath.begin(); it != curPath.end(); it++) {
if (it->second %2) {
odd++;
}
}
if (odd <= 1) return true;
return false;
}
void dfs(TreeNode* cur, unordered_map<int,int> &curPath) {
if (cur == nullptr) {
return;
}
curPath[cur->val]++;
if (cur->left == nullptr && cur->right == nullptr) {
res += isPseudoPa(curPath);
curPath[cur->val]--;
return;
}
dfs(cur->left, curPath);
dfs(cur->right, curPath);
curPath[cur->val]--;
}
int pseudoPalindromicPaths (TreeNode* root) {
unordered_map<int,int> mp;
dfs(root, mp);
return res;
}
};
/**
* 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 {
public:
int res = 0;
void dfs(TreeNode* cur, array<int, 10> &curPath) {
if (cur == nullptr) {
return;
}
curPath[cur->val] ^= 1;
if (cur->left == nullptr && cur->right == nullptr) {
res += accumulate(curPath.begin(), curPath.end(), 0) <= 1;
curPath[cur->val] ^= 1;
return;
}
dfs(cur->left, curPath);
dfs(cur->right, curPath);
curPath[cur->val] ^= 1;
}
int pseudoPalindromicPaths (TreeNode* root) {
array<int, 10> p{};
dfs(root, p);
return res;
}
};
/**
* 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 {
public:
int res = 0;
void dfs(TreeNode* cur, int mask) {
if (cur == nullptr) {
return;
}
mask ^= 1 << cur->val;
if (cur->left == nullptr && cur->right == nullptr) {
res += (mask == (mask & -mask) ? 1 : 0);
return;
}
dfs(cur->left, mask);
dfs(cur->right, mask);
}
int pseudoPalindromicPaths (TreeNode* root) {
dfs(root, 0);
return res;
}
};