-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathsecond-minimum-node-in-a-binary-tree.cpp
More file actions
57 lines (50 loc) · 1.32 KB
/
second-minimum-node-in-a-binary-tree.cpp
File metadata and controls
57 lines (50 loc) · 1.32 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
/**
* 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:
set<int> bag;
void kthSmall(TreeNode* root, int k) {
if ( root == nullptr ) { return; }
kthSmall(root->left, k);
if ( bag.count(root->val) == 0 ) {
bag.insert(root->val);
if ( size(bag) == k ) { return; }
}
kthSmall(root->right, k);
}
int findSecondMinimumValue(TreeNode* root) {
kthSmall(root, 2);
if ( size(bag) < 2 ) { return -1; }
return vector<int>(bag.begin(), bag.end()).at(1);
}
};
// Alternate
class Solution {
public:
void dfs(TreeNode* root,set<int>&s){
if(root == NULL)
return;
s.insert(root->val);
dfs(root->left,s);
dfs(root->right,s);
}
public:
int findSecondMinimumValue(TreeNode* root) {
set<int>s;
dfs(root,s);
auto it = s.begin();
it++;
if(s.size() == 1)
return -1;
return *it;
}
};