我无法理解这里使用的位掩码,给定的代码是在二进制树中寻找包含数字0-9(含)的字谜路径的解决方案。我已经在代码中用if语句标记了这一行。
这是LeetCode比赛的问题。问题是给定的。
二进制树中的伪平光路径,给定一棵二进制树 其中节点值是1到9的数字. 如果二进制树中至少有一个节点值的排列组合是一个倒序,那么这个路径就被称为伪倒序路径。
返回从根结点到叶结点的伪平顺路径的数量。
int pseudoPalindromicPaths (TreeNode* root) {
return dfs(root, 0);
}
int dfs(TreeNode* root, int count) {
if (!root) return 0;
count ^= 1 << (root->val - 1);
int res = dfs(root->left, count) + dfs(root->right, count);
if (root->left == root->right && (count & (count - 1)) == 0) res++;
//--------------------------------------^--THIS SECTION-----
count ^= 1 << (root->val - 1);
return res;
}
count & (count - 1) == 0
如果count是2的幂,那么这句话是真的。
例子: 计数=8
00001000 = 8
&
00000111 = (8-1) = 7
------------
00000000 = 0