-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1457.二叉树中的伪回文路径.cpp
65 lines (57 loc) · 1.65 KB
/
1457.二叉树中的伪回文路径.cpp
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
/*
* @lc app=leetcode.cn id=1457 lang=cpp
*
* [1457] 二叉树中的伪回文路径
*/
// @lc code=start
/**
* 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) {}
* };
*/
// 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) {}
// };
#include <unordered_map>
class Solution {
public:
int pseudoPalindromicPaths (TreeNode* root) {
dfs(root);
return result;
}
private:
int result = 0;
std::array<int, 10> nums_cnt;
int odd_cnt = 0;
int even_cnt = 0;
void dfs(TreeNode* node) {
bool flag = nums_cnt[node->val] % 2 == 0;
odd_cnt = flag ? odd_cnt + 1 : odd_cnt - 1;
even_cnt = flag ? even_cnt - 1 : even_cnt + 1;
nums_cnt[node->val]++;
if (node->left == nullptr && node->right == nullptr) {
if (odd_cnt <= 1) result++;
}
if (node->left != nullptr) {
dfs(node->left);
}
if (node->right != nullptr) {
dfs(node->right);
}
odd_cnt = flag ? odd_cnt - 1 : odd_cnt + 1;
even_cnt = flag ? even_cnt + 1 : even_cnt - 1;
nums_cnt[node->val]--;
}
};
// @lc code=end