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); } }};
- leetcode 671. Second Minimum Node In a Binary Tree 第二小数字 + 深度优先遍历DFS
- leetcode 671. Second Minimum Node In a Binary Tree
- leetcode 671. Second Minimum Node In a Binary Tree
- leetcode 671. Second Minimum Node In a Binary Tree
- LeetCode 671. Second Minimum Node In a Binary Tree
- Second Minimum Node In a Binary Tree:求二叉树第二小的值
- [LeetCode] Second Minimum Node In a Binary Tree
- LeetCode#671 Second Minimum Node In a Binary Tree (week13)
- 671. Second Minimum Node In a Binary Tree
- 671. Second Minimum Node In a Binary Tree
- 671. Second Minimum Node In a Binary Tree
- 671. Second Minimum Node In a Binary Tree
- 671. Second Minimum Node In a Binary Tree
- 671. Second Minimum Node In a Binary Tree
- 671. Second Minimum Node In a Binary Tree
- 671. Second Minimum Node In a Binary Tree
- Second Minimum Node In a Binary Tree问题及解法
- Leetcode671. Second Minimum Node In a Binary Tree
- 像大牛一样写代码:31个Android 开发者工具
- Python urllib&urllib2&httplib
- PHP常量
- iosSelect插件 H5中实现iOS的select下拉联动效果
- Qt 不响应鼠标事件
- leetcode 671. Second Minimum Node In a Binary Tree 第二小数字 + 深度优先遍历DFS
- MySQL基础教程之存储过程
- SpringBoot Logback根据日志级别分离日志
- ASP 上传图片文件,生成水印图片
- C++ \u中文乱码解决办法
- [FWT][BlueStein Algorithm]CodeChef XORTREEH
- 深度学习: Full Connection (全连接层)
- Vue前后端不同端口实现方案
- 蓝桥杯 算法训练 未名湖边的烦恼