-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSecondMinimumNodeInBinaryTree.cpp
58 lines (54 loc) · 1.22 KB
/
SecondMinimumNodeInBinaryTree.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
#include <iostream>
#include <vector>
#include <algorithm>
#include <set> // for duplicate handling
using namespace std;
// 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
{
private:
vector<int> preOrderVec;
public:
void preOrderTraversal(TreeNode *current) // VLR
{
if (current == nullptr)
{
return;
}
preOrderVec.push_back(current->val);
preOrderTraversal(current->left);
preOrderTraversal(current->right);
}
int findSecondMinimumValue(TreeNode *root)
{
preOrderTraversal(root);
sort(preOrderVec.begin(), preOrderVec.end());
set<int> s(preOrderVec.begin(), preOrderVec.end());
auto it = s.begin();
for (const int &i : s)
{
cout << i << endl;
}
int firstElement = *it;
advance(it, 1);
int secondElement = *it;
if (s.size() == 1)
{
return -1;
}
return secondElement;
}
};
int main()
{
return 0;
}