1 Star 0 Fork 0

yuhang2__2/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
pseudo-palindromic-paths-in-a-binary-tree.cpp 1.37 KB
一键复制 编辑 原始数据 按行查看 历史
// Time: O(n)
// Space: O(h)
/**
* 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) {
int result = 0;
vector<pair<TreeNode *, int>> stk = {{root, 0}};
while (!stk.empty()) {
auto [node, count] = stk.back(); stk.pop_back();
if (!node) {
continue;
}
count ^= 1 << node->val;
result += int(!node->left && !node->right && (count & (count - 1)) == 0);
stk.emplace_back(node->right, count);
stk.emplace_back(node->left, count);
}
return result;
}
};
// Time: O(n)
// Space: O(h)
class Solution2 {
public:
int pseudoPalindromicPaths (TreeNode* root) {
return dfs(root, 0);
}
private:
int dfs(TreeNode *node, int count) {
if (!node) {
return 0;
}
count ^= 1 << node->val;
return int(!node->left && !node->right && (count & (count - 1)) == 0) +
dfs(node->left, count) + dfs(node->right, count);
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/yuhang2__2/LeetCode-Solutions.git
git@gitee.com:yuhang2__2/LeetCode-Solutions.git
yuhang2__2
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助