671 Second Minimum Node In a Binary Tree

671. Second Minimum Node In a Binary Tree

1. Question

Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactlytwoorzerosub-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:
1
Input:
2
3
2
4
/ \
5
2 5
6
/ \
7
5 7
8
9
10
Output:
11
5
12
13
Explanation:
14
The smallest value is 2, the second smallest value is 5.
Copied!
Example 2:
1
Input:
2
3
2
4
/ \
5
2 2
6
7
8
Output:
9
-1
10
11
Explanation:
12
The smallest value is 2, but there isn't any second smallest value.
Copied!

2. Implementation

(1) BFS
1
class Solution {
2
public int findSecondMinimumValue(TreeNode root) {
3
if (root == null) {
4
return -1;
5
}
6
7
int min = Integer.MAX_VALUE, secondMin = Integer.MAX_VALUE;
8
Queue<TreeNode> queue = new LinkedList<>();
9
Set<Integer> set = new HashSet<>();
10
queue.add(root);
11
12
while (!queue.isEmpty()) {
13
int size = queue.size();
14
15
for (int i = 0; i < size; i++) {
16
TreeNode curNode = queue.remove();
17
18
if (curNode.left != null) {
19
queue.add(curNode.left);
20
}
21
22
if (curNode.right != null) {
23
queue.add(curNode.right);
24
}
25
26
if (set.contains(curNode.val)) {
27
continue;
28
}
29
30
set.add(curNode.val);
31
32
if (curNode.val < min) {
33
secondMin = min;
34
min = curNode.val;
35
}
36
else if (curNode.val < secondMin) {
37
secondMin = curNode.val;
38
}
39
}
40
}
41
return set.size() < 2 ? -1 : secondMin;
42
}
43
}
Copied!
(2) DFS
1
/**
2
* Definition for a binary tree node.
3
* public class TreeNode {
4
* int val;
5
* TreeNode left;
6
* TreeNode right;
7
* TreeNode(int x) { val = x; }
8
* }
9
*/
10
class Solution {
11
public int findSecondMinimumValue(TreeNode root) {
12
int[] res = new int[2];
13
Arrays.fill(res, Integer.MAX_VALUE);
14
Set<Integer> set = new HashSet();
15
dfs(root, set, res);
16
return set.size() < 2 ? -1 : res[0];
17
}
18
19
public void dfs(TreeNode node, Set<Integer> set, int[] res) {
20
if (node == null) return;
21
22
if (!set.contains(node.val)) {
23
set.add(node.val);
24
if (node.val < res[1]) {
25
res[0] = res[1];
26
res[1] = node.val;
27
}
28
else if (node.val < res[0]) {
29
res[0] = node.val;
30
}
31
}
32
33
dfs(node.left, set, res);
34
dfs(node.right, set, res);
35
}
36
}
Copied!

3. Time & Space Complexity

BFS: 时间复杂度O(n), 空间复杂度O(w)
DFS: 时间复杂度O(n), 空间复杂度O(h)