Posted on

Description

Submission

/**
 * 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 {
    int rootVal;
    int ret;

    void dfs(TreeNode* node) {
        if(!node) return;
        if(node->val == rootVal) {
            dfs(node->left);
            dfs(node->right);
        }
        if(node->val > rootVal) {
            if(ret < 0) ret = node->val;
            else ret = min(node->val, ret);
        }
    }
public:
    int findSecondMinimumValue(TreeNode* root) {
        if(!root) return -1;
        rootVal = root->val;
        ret = -1;

        dfs(root);

        return ret;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *