Second Minimum Node In a Binary Tree

2019-05-25 22:40:20 浏览数 (1)

1. Description

2. Solution

代码语言:javascript复制
/**
 * 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);
    }
};

0 人点赞