# 671.Second Minimum Node in a Binary Tree

671.Second Minimum Node in a Binary Tree 难度:Easy

> 给定一个非空特殊的二叉树，每个节点都是正数，并且每个节点的子节点数量只能为 2 或 0。如果一个节点有两个子节点的话，那么这个节点的值不大于它的子节点的值。

给出这样的一个二叉树，你需要输出所有节点中的第二小的值。如果第二小的值不存在的话，输出 -1 。

```
示例 1:

输入: 
    2
   / \
  2   5
     / \
    5   7

输出: 5
说明: 最小的值是 2 ，第二小的值是 5 。
示例 2:

输入: 
    2
   / \
  2   2

输出: -1
说明: 最小的值是 2, 但是不存在第二小的值。
```

二叉樹的遍歷，不過需要注意的是，需要計數幾個不同的數來判斷是否存在第二小的數。

```
/**
 * 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 {
int min_fir=INT_MAX;
int min_sec=min_fir;
int count=0;
void traversal(TreeNode* root)
{
    if(!root)  return;
        if(root->val < min_fir) {min_sec=min_fir; min_fir=root->val ; ++count;}
        else if(root->val > min_fir && root->val <= min_sec) { min_sec=root->val; ++count;}
       
        if(root->left )
        {
            traversal(root->left);
            traversal(root->right);
        }
}
public:
    int findSecondMinimumValue(TreeNode* root) {
        traversal(root);
       // cout<<min_fir<<"   "<< min_sec<<endl;
        //cout<<count<<endl;
        return count<2 ? -1 : min_sec;
        
    }
};
```

> 执行用时 :4 ms, 在所有 C++ 提交中击败了83.38%的用户\
> 内存消耗 :8.4 MB, 在所有 C++ 提交中击败了95.10%的用户


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://dfine.gitbook.io/leetcode/671.second_minimum_node_in_a_binary_tree.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
