给你一棵二叉树,每个节点的值为 1 到 9 。我们称二叉树中的一条路径是 「伪回文」的,当它满足:路径经过的所有节点值的排列中,存在一个回文序列。
请你返回从根到叶子节点的所有路径中 伪回文 路径的数目。
示例 1:
![](https://img-blog.csdnimg.cn/img_convert/45d951e5a751c5eb438fce12725aa50d.png)
输入:root = [2,3,1,3,1,null,1]
输出:2
解释:上图为给定的二叉树。总共有 3 条从根到叶子的路径:红色路径 [2,3,3] ,绿色路径 [2,1,1] 和路径 [2,3,1] 。
在这些路径中,只有红色和绿色的路径是伪回文路径,因为红色路径 [2,3,3] 存在回文排列 [3,2,3] ,绿色路径 [2,1,1] 存在回文排列 [1,2,1] 。
示例 2:
![](https://img-blog.csdnimg.cn/img_convert/5fd5eff6e946816b7bde2ab3d2cd1b65.png)
输入:root = [2,1,1,1,3,null,null,null,null,null,1]
输出:1
解释:上图为给定二叉树。总共有 3 条从根到叶子的路径:绿色路径 [2,1,1] ,路径 [2,1,3,1] 和路径 [2,1] 。
这些路径中只有绿色路径是伪回文路径,因为 [2,1,1] 存在回文排列 [1,2,1] 。
示例 3:
输入:root = [9]
输出:1
提示:
给定二叉树的节点数目在范围 [1, 105] 内
1 <= Node.val <= 9
1457. 二叉树中的伪回文路径 - 力扣(Leetcode)
思路:
利用 dfs遍历二叉树,得到所有到达叶子节点的路径,并判断该路径是否为伪回文;
判断一个数组是否可以排列为回文:
1.当 path 为偶数时,其中所有元素出现的次数均为偶数时,才有可能排列为回文数组;
2. 当 path 为奇数时,其中只有一个元素出现的次数为奇数,其余元素出现的次数均为 偶数,才有可能排列为回文数组
c++:
/**
* 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 result = 0;
int pseudoPalindromicPaths (TreeNode* root) {
if(root == nullptr) {
return 0;
}
vector<int> path;
dfs(root, path);
return result;
}
void dfs(TreeNode* root, vector<int>& path) {
if(root == nullptr) {
return;
}
path.push_back(root->val);
// 当前节点为叶子节点时,判断当前路径是否为伪回文路径
if(root->left == nullptr && root->right == nullptr) {
if(isPseudoPalindromic(path)) {
result += 1;
}
} else {
dfs(root->left, path);
dfs(root->right, path);
}
path.pop_back();
}
// 当 path 为偶数时,其中所有元素出现的次数均为偶数时,才有可能排列为回文数组;
// 当 path 为奇数时,其中只有一个元素出现的次数为奇数,其余元素出现的次数均为 偶数,才有可能排列为回文数组
bool isPseudoPalindromic(vector<int>& path) {
map<int, int> count_map;
for(auto a:path) {
if(count_map.count(a)) {
count_map[a] += 1;
} else {
count_map[a] = 1;
}
}
int even_num = 0;
int odd_num = 0;
for(auto iter = count_map.begin(); iter != count_map.end(); iter++) {
if(iter->second % 2 == 0) {
even_num += 1;
} else {
odd_num += 1;
}
}
if(path.size() % 2 == 0) {
if(odd_num == 0) {
return true;
} else {
return false;
}
} else {
if(odd_num == 1) {
return true;
} else {
return false;
}
}
}
};