Leetcode 671 Solution

This article provides solution to leetcode question 671 (second-minimum-node-in-a-binary-tree)

https://leetcode.com/problems/second-minimum-node-in-a-binary-tree

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) {
        queue<TreeNode*> q;

        q.push(root);

        long long int min1 = 100000000000L;
        long long int min2 = 100000000000L;

        while (!q.empty())
        {
            auto node = q.front();
            q.pop();

            if (node->val < min1)
            {
                min2 = min1;
                min1 = node->val;
            }
            else if (node->val < min2 && node->val != min1)
                min2 = node->val;

            if (node->left)
                q.push(node->left);
            if (node->right)
                q.push(node->right);
        }

        return min2 != 100000000000L ? min2 : -1;
    }
};