leetcode 671. Second Minimum Node In a Binary Tree 第二小数字 + 深度优先遍历DFS

来源:互联网 发布:php array push 键值 编辑:程序博客网 时间:2024/05/22 07:58

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.

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.

这道题题意很简单,首先root结点就是最小的值,那么遍历一次即可找到第二小的值

代码如下:

#include <iostream>#include <vector>#include <map>#include <set>#include <queue>#include <stack>#include <string>#include <climits>#include <algorithm>#include <sstream>#include <functional>#include <bitset>#include <numeric>#include <cmath>#include <regex>using namespace std;/*struct TreeNode {     int val;     TreeNode *left;     TreeNode *right;     TreeNode(int x) : val(x), left(NULL), right(NULL) {}};*/class Solution {public:    int findSecondMinimumValue(TreeNode* root)     {        if (root == NULL)            return -1;        int min = root->val;        int secMin = INT_MAX;        dfs(root,min,secMin);        if (secMin == INT_MAX || min == secMin)            return -1;        else            return secMin;    }    void dfs(TreeNode* root,int& min,int& secMin)    {        if (root != NULL)        {            if (root->val != min && root->val < secMin)                secMin = root->val;            dfs(root->left, min, secMin);            dfs(root->right, min, secMin);        }    }};
阅读全文
0 0
原创粉丝点击