-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKmit.cpp
61 lines (48 loc) · 1.37 KB
/
Kmit.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
#include<iostream>
#include<vector>
#include<queue>
#include<climits>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int value) : val(value), left(NULL), right(NULL) {}
};
int findSecondMinimumValue(TreeNode* root) {
if (!root) {
return -1; // Invalid input or no nodes in the tree
}
int firstMin = root->val;
long long secondMin = LLONG_MAX;
queue<TreeNode*>q;
q.push(root);
while (!q.empty()) {
TreeNode* current = q.front();
q.pop();
if (current->val > firstMin && current->val < secondMin) {
secondMin = current->val;
}
if (current->left) {
q.push(current->left);
q.push(current->right);
}
}
return (secondMin == LLONG_MAX) ? -1 : secondMin;
}
int main() {
// Sample Input: {2, 2, 5, NULL, NULL, 5, 7}
TreeNode* root = new TreeNode(2);
root->left = new TreeNode(2);
root->right = new TreeNode(5);
root->right->left = NULL;
root->right->right = NULL;
root->right->left = new TreeNode(5);
root->right->right = new TreeNode(7);
int secondMin = findSecondMinimumValue(root);
if (secondMin != -1) {
cout << "The second minimum node in the binary tree is: " << secondMin << endl;
} else {
cout << "No second minimum node found." << endl;
}
return 0;
}