-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathSecond_Minimum_Node_In_a_Binary_Tree.cpp
More file actions
32 lines (29 loc) · 1.02 KB
/
Second_Minimum_Node_In_a_Binary_Tree.cpp
File metadata and controls
32 lines (29 loc) · 1.02 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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
void findSecondMinimumValue(TreeNode* root, const int minimum, int& secondMinimum) {
if(!root) return;
if(root->val > minimum) {
secondMinimum = (secondMinimum != -1) ? min(secondMinimum, root->val) : root->val;
}
if(root->right != nullptr and root->right->val > root->val) {
secondMinimum = (secondMinimum != -1) ? min(secondMinimum, root->right->val) : root->right->val;
} else {
findSecondMinimumValue(root->right, minimum, secondMinimum);
}
findSecondMinimumValue(root->left, minimum, secondMinimum);
}
public:
int findSecondMinimumValue(TreeNode* root) {
int secondMinimum = -1;
findSecondMinimumValue(root, root->val, secondMinimum);
return secondMinimum;
}
};