Leetcode 671. Second Minimum Node In a Binary Tree

版权声明:博客文章都是作者辛苦整理的,转载请注明出处,谢谢! https://blog.csdn.net/Quincuntial/article/details/84960057

文章作者: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/

没有更多推荐了,返回首页

私密
私密原因:
请选择设置私密原因
  • 广告
  • 抄袭
  • 版权
  • 政治
  • 色情
  • 无意义
  • 其他
其他原因:
120
出错啦
系统繁忙,请稍后再试