-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1457.pseudo-palindromic-paths-in-a-binary-tree.cpp
84 lines (73 loc) · 1.88 KB
/
1457.pseudo-palindromic-paths-in-a-binary-tree.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/*
@lc app=leetcode.cn id=1457 lang=cpp
@lcpr version=30111
*
[1457] 二叉树中的伪回文路径
*/
// @lcpr-template-start
#include <algorithm>
#include <array>
#include <bitset>
#include <climits>
#include <deque>
#include <functional>
#include <iostream>
#include <list>
#include <queue>
#include <stack>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
using namespace std;
// @lcpr-template-end
// @lc code=start
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 cnt=0;
stack<pair<TreeNode*,unsigned int> >treeTrav;// <node,flag>
treeTrav.push({root,1<<(root->val)});
while (treeTrav.empty()==false)
{
auto last=treeTrav.top();
treeTrav.pop();
if(last.first->left==nullptr&&last.first->right==nullptr&&__builtin_popcount(last.second)<=1)
{
// cout<<last.first->val<<" -> "<<bitset<10>(last.second)<<endl;
cnt++;
}
if(last.first->left!=nullptr)
{
treeTrav.push({last.first->left,last.second^(1<<(last.first->left->val))});
}
if(last.first->right!=nullptr)
{
treeTrav.push({last.first->right,last.second^(1<<(last.first->right->val))});
}
}
return cnt;
}
};
// @lc code=end
/*
// @lcpr case=start
// [2,3,1,3,1,null,1]\n
// @lcpr case=end
// @lcpr case=start
// [2,1,1,1,3,null,null,null,null,null,1]\n
// @lcpr case=end
// @lcpr case=start
// [9]\n
// @lcpr case=end
*/