题目:
Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be pseudo-palindromic if at least one permutation of the node values in the path is a palindrome.
Return the number of pseudo-palindromic paths going from the root node to leaf nodes.
Example 1:
Input: root = [2,3,1,3,1,null,1] Output: 2 Explanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the red path [2,3,3], the green path [2,1,1], and the path [2,3,1]. Among these paths only red path and green path are pseudo-palindromic paths since the red path [2,3,3] can be rearranged in [3,2,3] (palindrome) and the green path [2,1,1] can be rearranged in [1,2,1] (palindrome).
Example 2:
Input: root = [2,1,1,1,3,null,null,null,null,null,1] Output: 1 Explanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the green path [2,1,1], the path [2,1,3,1], and the path [2,1]. Among these paths only the green path is pseudo-palindromic since [2,1,1] can be rearranged in [1,2,1] (palindrome).
Example 3:
Input: root = [9] Output: 1
Constraints:
- The given binary tree will have between
1
and10^5
nodes. - Node values are digits from
1
to9
.
思路:
题目给了hint,用DFS记录整条path上的数,然后出现次数为奇数的数字只能小于等于1,否则不对称,这个逻辑很清楚就不证明了。这里我选择的容器时哈希set,每次遇到一个数先检查有没有,如果没有就加入set,如果有就说明已经出现过一次了,从set中删去,这样最后走完的时候,set中剩余的size就是这条路上出现次数为奇数的数的数量(有点绕不过逻辑很简单)。这里还有一个点就是需要检查叶子节点,dfs的base case不能是当前root为空,因为叶子节点会造成左右两个空结点,这样最终算出来的结果是真实结果的两倍,这里可能会想到直接把结果除以2即可,这也是错的。因为有可能某个节点是有左无右,这样就凭白造成了一个空结点,也就是一个结算点。因此要确认到叶子节点再做成base case,这就导致在初始函数我们要先确认给定root是不是为空。
代码:
/**
* 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 pseudoPalindromicPaths (TreeNode* root) {
if(!root)
return 0;
unordered_set<int> s;
check(root,s);
return count;
}
private:
int count=0;
void check(TreeNode* root, unordered_set<int> s)
{
if(s.count(root->val))
s.erase(root->val);
else
s.insert(root->val);
if(!root->left&&!root->right)
{
if(s.size()<=1)
count+=1;
return ;
}
if(root->left)
check(root->left,s);
if(root->right)
check(root->right,s);
}
};