• Time:O(n)
• Space:O(h)

## C++

``````class Solution {
public:
int pseudoPalindromicPaths(TreeNode* root) {
int ans = 0;
dfs(root, 0, ans);
return ans;
}

private:
void dfs(TreeNode* root, int path, int& ans) {
if (!root)
return;
if (!root->left && !root->right) {
path ^= 1 << root->val;
if ((path & (path - 1)) == 0)
++ans;
return;
}

dfs(root->left, path ^ 1 << root->val, ans);
dfs(root->right, path ^ 1 << root->val, ans);
}
};
``````

## JAVA

``````class Solution {
public int pseudoPalindromicPaths(TreeNode root) {
dfs(root, 0);
return ans;
}

private int ans = 0;

private void dfs(TreeNode root, int path) {
if (root == null)
return;
if (root.left == null && root.right == null) {
path ^= 1 << root.val;
if ((path & (path - 1)) == 0)
++ans;
return;
}

dfs(root.left, path ^ 1 << root.val);
dfs(root.right, path ^ 1 << root.val);
}
}
``````

## Python

``````class Solution:
def pseudoPalindromicPaths(self, root: Optional[TreeNode]) -> int:
ans = 0

def dfs(root: Optional[TreeNode], path: int) -> None:
nonlocal ans
if not root:
return
if not root.left and not root.right:
path ^= 1 << root.val
if path & (path - 1) == 0:
ans += 1
return

dfs(root.left, path ^ 1 << root.val)
dfs(root.right, path ^ 1 << root.val)

dfs(root, 0)
return ans
``````