671. Second Minimum Node In a Binary Tree

671. Second Minimum Node In a Binary Tree

题目描述

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.

1
2
3
4
5
6
7
8
9
10
Example 1:
Input:
2
/ \
2 5
/ \
5 7
Output: 5
Explanation: The smallest value is 2, the second smallest value is 5.
1
2
3
4
5
6
7
8
Example 2:
Input:
2
/ \
2 2
Output: -1
Explanation: The smallest value is 2, but there isn't any second smallest value.

题目大意

给定一非空的特殊二叉树,每个节点都有0个或者2个节点,根节点是子节点中的较小
找到二叉树内,节点值第二小的节点,如果有返回节点值,否则返回-1

解题思路

找到二叉树内比根节点大的所有节点中的最小值。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init(_ val: Int) {
* self.val = val
* self.left = nil
* self.right = nil
* }
* }
*/
class Solution {
func findSecondMinimumValue(_ root: TreeNode?) -> Int {
guard let tree = root else { return -1 }
var ans = Int.max
var min = tree.val
func find(root: TreeNode?) {
guard let tree = root else { return }
if tree.val < ans && tree.val > min {
ans = tree.val
}
find(root: tree.left)
find(root: tree.right)
}
find(root: tree)
return ans == Int.max ? -1 : ans
}
}
0%