-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpseudoPalindromicPaths.cpp
More file actions
81 lines (79 loc) · 1.79 KB
/
pseudoPalindromicPaths.cpp
File metadata and controls
81 lines (79 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/**
* 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 {
private:
int odd_count = 0, ans = 0;
unordered_map<int, int> count;
public:
void dfs (TreeNode *root) {
int e = root->val;
++count[e];
if (count[e] & 1) {
++odd_count;
}
else {
--odd_count;
}
if (!root->left && !root->right) {
if (odd_count <= 1) {
++ans;
}
}
else {
if (root->left) {
dfs(root->left);
}
if (root->right) {
dfs(root->right);
}
}
--count[e];
if (count[e] & 1) {
++odd_count;
}
else {
--odd_count;
}
}
int pseudoPalindromicPaths (TreeNode* root) {
odd_count = ans = 0;
count.clear();
dfs(root);
return ans;
}
};
// Bit
class Solution {
private:
int ans = 0;
public:
void dfs (TreeNode *root, int count) {
count ^= (1 << root->val);
if (!root->left && !root->right) {
if (!count || !(count & (count - 1))) {
++ans;
}
}
else {
if (root->left) {
dfs(root->left, count);
}
if (root->right) {
dfs(root->right, count);
}
}
}
int pseudoPalindromicPaths (TreeNode* root) {
dfs(root, 0);
return ans;
}
};