您的位置:首页 > Web前端 > Node.js

Second Minimum Node In a Binary Tree:求二叉树第二小的值

2017-11-16 08:15 323 查看
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.

思路:保存所有节点的值,找出第二小,时空复杂度均为O(n)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public void dfs(TreeNode n,Set<Integer> set){
if(n==null) return;
set.add(n.val);
dfs(n.left,set);
dfs(n.right,set);
}

public int findSecondMinimumValue(TreeNode root) {
Set<Integer> set = new HashSet<Integer>();
dfs(root,set);
int min1 = root.val;
int ans = Integer.MAX_VALUE;
for (int v : set) {
if (min1 < v && v < ans) ans = v;
}
return ans < Integer.MAX_VALUE ? (int) ans : -1;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: