Skip to content

Commit cbebd5f

Browse files
authored
Create pseudo-palindromic-paths-in-a-binary-tree.cpp
1 parent ccb7f36 commit cbebd5f

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
// Time: O(n)
2+
// Space: O(h)
3+
4+
/**
5+
* Definition for a binary tree node.
6+
* struct TreeNode {
7+
* int val;
8+
* TreeNode *left;
9+
* TreeNode *right;
10+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
11+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
12+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
13+
* };
14+
*/
15+
16+
class Solution {
17+
public:
18+
int pseudoPalindromicPaths (TreeNode* root) {
19+
int result = 0;
20+
vector<pair<TreeNode *, int>> stk = {{root, 0}};
21+
while (!stk.empty()) {
22+
auto [node, count] = stk.back(); stk.pop_back();
23+
if (!node) {
24+
continue;
25+
}
26+
count ^= 1 << node->val;
27+
result += int(!node->left && !node->right && (count & (count - 1)) == 0);
28+
stk.emplace_back(node->right, count);
29+
stk.emplace_back(node->left, count);
30+
}
31+
return result;
32+
}
33+
};
34+
35+
// Time: O(n)
36+
// Space: O(h)
37+
class Solution2 {
38+
public:
39+
int pseudoPalindromicPaths (TreeNode* root) {
40+
return dfs(root, 0);
41+
}
42+
43+
private:
44+
int dfs(TreeNode *node, int count) {
45+
if (!node) {
46+
return 0;
47+
}
48+
count ^= 1 << node->val;
49+
return int(!node->left && !node->right && (count & (count - 1)) == 0) +
50+
dfs(node->left, count) + dfs(node->right, count);
51+
}
52+
};

0 commit comments

Comments
 (0)