671. Second Minimum Node In a Binary Tree*

671. Second Minimum Node In a Binary Tree*

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

题目描述

Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly two or zero sub-node. If the node has two sub-nodes, then this node’s value is the smaller value among its two sub-nodes. More formally, the property root.val = min(root.left.val, root.right.val) always holds.

Given such a binary tree, you need to output the second minimum value in the set made of all the nodes’ value in the whole tree.

If no such second minimum value exists, output -1 instead.

Example 1:

Input: 
    2
   / \
  2   5
     / \
    5   7

Output: 5
Explanation: The smallest value is 2, the second smallest value is 5.

Example 2:

Input: 
    2
   / \
  2   2

Output: -1
Explanation: The smallest value is 2, but there isn't any second smallest value.

C++ 实现 1

做这道题我凭着多年的经验避开了一个坑, 所以一把通过了. 具体思路我采用前序遍历来做. 这样的做法我感觉不符合题目的意图.

看下面的代码, 我避开的坑是 firstsecond 都设置为 long long 而不是 int. 后来我看其他人的解答时发现, 他们也用 long 类型, 那估计就是考虑到了可能会有一些无语的测试用例使用这种比较极端的值.

/**
 * 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 {
private:
    long long first = INT64_MAX, second = INT64_MAX;
    void preorder(TreeNode *root) {
        if (!root) return;
        if (root->val < first) {
            second = first;
            first = root->val;
        } else if (root->val > first && root->val < second) {
            second = root->val;
        }
        preorder(root->left);
        preorder(root->right);
    }
public:
    int findSecondMinimumValue(TreeNode* root) {
        preorder(root);
        if (second == INT64_MAX) return -1;
        return second;
    }
};
发布了352 篇原创文章 · 获赞 7 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Eric_1993/article/details/104547514