文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
2. Solution
/**
* 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 {
public:
int findSecondMinimumValue(TreeNode* root) {
int minimum = INT_MAX;
int secondMinimum = -1;
dfs(root, minimum, secondMinimum);
if(secondMinimum == minimum) {
return -1;
}
return secondMinimum;
}
private:
void dfs(TreeNode* root, int& minimum, int& secondMinimum) {
if(!root) {
return;
}
if(root->val < minimum) {
minimum = root->val;
secondMinimum = minimum;
}
if(root->val > minimum && (secondMinimum == minimum || root->val < secondMinimum)) {
secondMinimum = root->val;
}
dfs(root->left, minimum, secondMinimum);
dfs(root->right, minimum, secondMinimum);
}
};