美文网首页Leetcode
Leetcode 671. Second Minimum Nod

Leetcode 671. Second Minimum Nod

作者: SnailTyan | 来源:发表于2018-12-11 19:05 被阅读1次

    文章作者:Tyan
    博客:noahsnail.com  |  CSDN  |  简书

    1. Description

    Second Minimum Node In a Binary Tree

    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);
        }
    };
    

    Reference

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

    相关文章

      网友评论

        本文标题:Leetcode 671. Second Minimum Nod

        本文链接:https://www.haomeiwen.com/subject/bewehqtx.html