671. Second Minimum Node In a Binary Tree
来源:互联网 发布:淘宝客采集软件有哪些 编辑:程序博客网 时间:2024/06/04 18:47
题目描述
Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactlytwo
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 7Output: 5Explanation: The smallest value is 2, the second smallest value is 5.
Example 2:
Input: 2 / \ 2 2Output: -1Explanation: The smallest value is 2, but there isn't any second smallest value.
解题思路:
这个题目首先遍历一遍求出最大值,然后将min与min_next赋值给最大值。然后二次遍历,找到次小值就可以了。
时间复杂度是O(n)
解答代码:
/**
* 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 min,minn=-1;
void get_minn(TreeNode* root)
{
if(root)
{
if(minn < root->val)
min = minn = root->val;
get_minn(root->left);
get_minn(root->right);
}
}
void preorder(TreeNode* root)
{
if(root)
{
if(root->val < min )
{
minn = min;
min = root->val;
}
if(root->val <minn && root->val >min)
minn = root->val;
preorder(root->left);
preorder(root->right);
}
}
int findSecondMinimumValue(TreeNode* root) {
if( root==NULL || (root->left==NULL&&root->right==NULL&&root!=NULL) )
return -1;
int min = root->val;
get_minn(root);
preorder(root);
if(minn == min)
return -1;
return minn;
}
};
- 671. Second Minimum Node In a Binary Tree
- leetcode 671. Second Minimum Node In a Binary Tree
- 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
- 671. Second Minimum Node In a Binary Tree
- 671. Second Minimum Node In a Binary Tree
- 671. Second Minimum Node In a Binary Tree
- LeetCode 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
- [LeetCode] Second Minimum Node In a Binary Tree
- LeetCode#671 Second Minimum Node In a Binary Tree (week13)
- LeetCode671. Second Minimum Node In a Binary Tree
- leetcode 671. Second Minimum Node In a Binary Tree 第二小数字 + 深度优先遍历DFS
- hdu 6007 Mr. Panda and Crystal(最短路+完全背包)
- [译]我的go语言使用场景
- can not be represented as java.sql.Timestamp
- Java学习第五课
- 《程序设计入门—Java语言.翁恺》第二周编程作业(1)-时间转换
- 671. Second Minimum Node In a Binary Tree
- bat面试题 python 单链表反转排序
- 接口,继承的意义和使用方法
- 成为Java顶尖程序员 ,看这11本书就够了 以下是我推荐给Java开发者们的一些值得一看的好书。但是这些书里面并没有Java基础、Java教程之类的书,不是我不推荐,而是离我自己学习 Java基础技
- Tensorflow学习笔记(三)--变量作用域
- linux系统基本命令之文件和目录管理及vim,正则表达式
- Java学习第六天
- Spring FactoryBean
- 文章标题