671. Second Minimum Node In a Binary Tree 非递减二叉树中第二小的元素

时间:2021-10-22 21:32:40

[抄题]:

Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly twoor 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.

[暴力解法]:

时间分析:

空间分析:

[奇葩输出条件]:

要判断节点值是不是空节点产生的-1

[奇葩corner case]:

光有一个头节点,也无法输出

[思维问题]:

以为要用break:好像总体来说用得并不多,此题中只要判断是否不相等就行了

[一句话思路]:

DC女王算法只是一种思想,没有具体成型的模板

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

  1. traverse的表达式自身就带有递归循环的效果,不用再加while了。用于改变left的值,就必须把left放在左边

[二刷]:

[三刷]:

[四刷]:

[五刷]:

[五分钟肉眼debug的结果]:

[总结]:

能用等号就少用break

[复杂度]:Time complexity: O(n) Space complexity: O(n)

[英文数据结构或算法,为什么不用别的数据结构或算法]:

dc的思想其实没有什么普适性

[关键模板化代码]:

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

230. Kth Smallest Element in a BST 第k小,用二分法

[代码风格] :

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int findSecondMinimumValue(TreeNode root) {
//corner case
if (root == null) {
return -1;
}
if (root.left == null && root.right == null) {
return -1;
}
//define left, right first
int left = root.left.val;
int right = root.right.val;
//find next
if (left == root.val) {
left = findSecondMinimumValue(root.left);
}
if (right == root.val) {
right = findSecondMinimumValue(root.right);
}
//compare
if (left != -1 && right != -1) {
return Math.min(left, right);
}else if (left != -1) {
return left;
}else {
return right;
}
}
}